NET Core如何在Web API中自定义错误响应? [英] How to customize error response in web api with .net core?
问题描述
我正在将.net core 2.2与Web api一起使用.我创建了一个类,如下所示:
I am using .net core 2.2 with web api. I have created one class i.e. as below :
public class NotificationRequestModel
{
[Required]
public string DeviceId { get; set; }
[Required]
public string FirebaseToken { get; set; }
[Required]
public string OS { get; set; }
public int StoreId { get; set; }
}
使用上面的类,我创建了一个方法.现在,我想返回自定义对象,但它返回的是自己的对象. API方法是:
Using above class I have created one method. Now I want to return custom object but it's return it's own object. API method is :
public ActionResult<bool> UpdateFirebaseToken(NotificationRequestModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(FormatOutput(ModelState.Values));
}
var result = _notificationService.InsertOrUpdateFirebaseToken(model);
return Ok(result);
}
FormatOutput
这里的方法是格式化输出.
Here FormatOutput
method is format the output.
protected Base FormatOutput(object input, int code = 0, string message = "", string[] details = null)
{
Base baseResult = new Base();
baseResult.Status = code;
baseResult.Error = message;
baseResult.TimeStamp = CommonHelper.CurrentTimeStamp;
baseResult.Code = code;
baseResult.Details = details;
baseResult.Message = message; //Enum.Parse<APIResponseMessageEnum>(code.ToString(), true); // (enum of code get value from language)
return baseResult;
}
但是问题在于它返回了:
But the issue is it returns :
{ 错误":{ 设备ID": [ "DeviceId字段为必填." ] }, "title":发生一个或多个验证错误.", 状态":400, "traceId":"80000049-0001-fc00-b63f-84710c7967bb" }
{ "errors": { "DeviceId": [ "The DeviceId field is required." ] }, "title": "One or more validation errors occurred.", "status": 400, "traceId": "80000049-0001-fc00-b63f-84710c7967bb" }
我想用我的模型自定义此错误.我需要错误消息和返回输出的详细信息,并将其传递给我的模型.我怎样才能做到这一点?我曾尝试调试我的代码,发现API方法上的断点未调用.所以我无法处理我的自定义方法.有什么解决办法吗?我究竟做错了什么?任何帮助都感激不尽.谢谢你.
I want to customize this error with my model. I need error message and details from return output and passed it to my model. How can I do that? I had try to debug my code and found that breakpoint on API method is not calling. So I can't handle my custom method. Is there any solution? What am I doing wrong? Any help will be much appreciated. Thank you.
推荐答案
As Chris analized, your issue is caused by Automatic HTTP 400 responses .
对于快速解决方案,您可以通过
For the quick solution, you could supress this feature by
services.AddMvc()
.ConfigureApiBehaviorOptions(options => {
options.SuppressModelStateInvalidFilter = true;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
为了提高效率,您可以遵循克里斯的建议,如下所示:
For a efficient, you could follow suggestion from Chris, like below:
services.AddMvc()
.ConfigureApiBehaviorOptions(options => {
//options.SuppressModelStateInvalidFilter = true;
options.InvalidModelStateResponseFactory = actionContext =>
{
var modelState = actionContext.ModelState.Values;
return new BadRequestObjectResult(FormatOutput(modelState));
};
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
而且,您无需在操作中再定义下面的代码.
And, there is no need to define the code below any more in your action.
if (!ModelState.IsValid)
{
return BadRequest(FormatOutput(ModelState.Values));
}
这篇关于NET Core如何在Web API中自定义错误响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!