.Net Core WebApi 模型验证无效时报400

 

webapi默认处理了模型验证,所以会返回自带的格式,若我们想返回自定义的格式,就需要关闭它

然后自行获取。

 

主要是下面标红这句:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
            "https://httpstatuses.com/404";
        options.DisableImplicitFromServicesParameters = true;
    });

然后写个过滤器,自定义验证

    public class ValidateFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {

                JsonCode jc = new JsonCode();

                var modelState = context.ModelState;
                if (modelState != null)
                {
                    jc.code = -1000;
                    jc.msg = "验证失败";
                    jc.data = modelState.Keys
     .SelectMany(key => modelState[key].Errors.Select(x => new { field = key, message = x.ErrorMessage }));

                    context.Result = new ObjectResult(jc);
                    return;
                }

            }
        }
    }
    public class JsonCode
    {
        public int code { get; set; }
        public string msg { get; set; }
        public object data { get; set; }
    }

注入全局过滤器:

builder.Services.AddControllers(options => {
    options.Filters.Add(typeof(ValidateFilter));
}).

这样即可,返回格式如下:

{
  "code": -1000,
  "msg": "验证失败",
  "data": [
    {
      "field": "desc",
      "message": "至少10个字符"
    }
  ]
}

前端根据返回的状态码进行处理和显示。

可以参考以下文章:

https://learn.microsoft.com/zh-cn/aspnet/core/web-api/?view=aspnetcore-3.1#automatic-http-400-responses

https://www.coder.work/article/2977081

https://www.cnblogs.com/EminemJK/p/11498852.html

 

关注我的个人公众号,每日更新,获取更多技术知识

posted @ 2023-09-20 15:12  黄明辉  阅读(347)  评论(0编辑  收藏  举报