2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
嘗試使用FormatOutput如下方法自定義 BadRequest 響應(yīng):
services.AddMvc()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = actionContext =>
{
return new BadRequestObjectResult(FormatOutput(actionContext.ModelState));
};
});
FormatOutput根據(jù)您的想法定制方法。
public List<Base> FormatOutput(ModelStateDictionary input)
{
List<Base> baseResult = new List<Base>();
foreach (var modelStateKey in input.Keys)
{
var modelStateVal = input[modelStateKey];
foreach (ModelError error in modelStateVal.Errors)
{
Base basedata = new Base();
basedata.Status = StatusCodes.Status400BadRequest;
basedata.Field = modelStateKey;
basedata.Message =error.ErrorMessage; // set the message you want
baseResult.Add(basedata);
}
}
return baseResult;
}
public class Base
{
public int Status { get; set; }
public string Field { get; set; }
public string Message { get; set; }
}

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
要根據(jù)您的用例添加自定義響應(yīng),請(qǐng)?jiān)?strong>啟動(dòng)中添加以下代碼
services.Configure<ApiBehaviorOptions>(o =>
{
? ? o.InvalidModelStateResponseFactory = actionContext =>
? ? ? ? new ResponseObject("403", "processing error");
});
其中ResponseObject是自定義類
?class ResponseObject{
? ?public string Status;
? ?public string Message;
? ?ResponseObject(string Status, string Message){
? ? ?this.Status = Status;
? ? ?this.Message= Message;
? ?}
?}
當(dāng)模型綁定失敗時(shí) api 會(huì)返回這樣的響應(yīng)
{ 狀態(tài):“403”,消息:“處理錯(cuò)誤”}
您可以根據(jù)需要自定義響應(yīng)對(duì)象。
- 2 回答
- 0 關(guān)注
- 289 瀏覽
添加回答
舉報(bào)