为了账号安全,请及时绑定邮箱和手机立即绑定

模型绑定失败时的自定义响应 ASP.NET Core API

模型绑定失败时的自定义响应 ASP.NET Core API

C#
繁花不似锦 2023-07-23 14:22:02
当模型绑定因数据类型不匹配而失败时,我想给出自定义响应。API示例:当有人尝试将参数绑定string到GUID我的 API 中时,当前我收到以下响应。    {      "documentCategoryId": [        "Error converting value \"string\" to type 'System.Guid'. Path 'documentCategoryId', line 2, position 32."      ]    }相反,我想说的是,处理错误
查看完整描述

2 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

尝试使用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; }

}


查看完整回答
反对 回复 2023-07-23
?
SMILET

TA贡献1796条经验 获得超4个赞

要根据您的用例添加自定义响应,请在启动中添加以下代码


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”,消息:“处理错误”}


您可以根据需要自定义响应对象。


查看完整回答
反对 回复 2023-07-23
  • 2 回答
  • 0 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信