【问题标题】:Custom response when Model binding fails ASP.NET Core API模型绑定失败时的自定义响应 ASP.NET Core API
【发布时间】:2019-12-07 17:18:18
【问题描述】:

模型绑定API数据类型不匹配而失败时,我想给出一个自定义响应

示例:当有人尝试在我的 API 中将 string 绑定到 GUID 参数时,目前我得到以下响应。

    {
      "documentCategoryId": [
        "Error converting value \"string\" to type 'System.Guid'. Path 'documentCategoryId', line 2, position 32."
      ]
    }

相反,我想说,

处理错误

【问题讨论】:

标签: c# .net http asp.net-core-webapi


【解决方案1】:

尝试使用FormatOutput 方法自定义 BadRequest 响应,如下所示:

 services.AddMvc()
         .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    return new BadRequestObjectResult(FormatOutput(actionContext.ModelState));
                };
            });

随心所欲地自定义 FormatOutput 方法。

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

【讨论】:

    【解决方案2】:

    参考此post,要根据您的用例添加自定义响应,请在启动

    中添加以下代码
    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;
       }
     }
    

    当模型绑定失败时,api 会返回这样的响应

    { 状态:“403”,消息:“处理错误”}

    您可以随意自定义响应对象。

    【讨论】:

    • 我试过这个 Giddy,但不知道为什么控件没有点击这段代码,感谢您的帮助。
    猜你喜欢
    • 2019-05-10
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    相关资源
    最近更新 更多