如何使用.NET Core在Web API中自定义错误响应? [英] How can I customize the 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 the above class I have created one method. Now I want to return a custom object, but it's returning its 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;
}
但是问题在于它返回:
{
"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?
推荐答案
As Chris analyzed, your issue is caused by Automatic HTTP 400 responses.
对于快速解决方案,您可以通过以下方式取消此功能
For the quick solution, you could suppress this feature by
services.AddMvc()
.ConfigureApiBehaviorOptions(options => {
options.SuppressModelStateInvalidFilter = true;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
以一种有效的方式,您可以遵循克里斯的建议,如下所示:
For an efficient way, you could follow the 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 isn't any need to define the code below any more in your action.
if (!ModelState.IsValid)
{
return BadRequest(FormatOutput(ModelState.Values));
}
这篇关于如何使用.NET Core在Web API中自定义错误响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!