如何使用 .NET Core 自定义 Web API 中的错误响应? [英] How can I customize the error response in Web API with .NET Core?

查看:58
本文介绍了如何使用 .NET Core 自定义 Web API 中的错误响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 .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?

推荐答案

正如 Chris 分析的那样,您的问题是由 自动 HTTP 400回复.

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);

对于一种有效的方法,您可以遵循 Chris 的建议,如下所示:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆