亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

模型綁定失敗時的自定義響應 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 關注
  • 295 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號