当我们定义接口参数实体的时候,如设置:

public class LoginInput
{
    [Required]//必填属性,不能为空或空字符串
    public string Account { get; set; }

    [Required]
    public string Password { get; set; }
}

默认情况下,当这两个字段参数传入为空的时候,会错误返回如下数据:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|1e7aa4fe-434615f18efb5f45.",
  "errors": {
    "Account": [
      "The Account field is required."
    ],
    "Password": [
      "The Password field is required."
    ]
  }
}

但是一般情况下,我们都会有自己一套消息结构体的返回,而系统默认的数据结构体,不利于前端统一处理,所以我们需要能将
这类型的错误返回也能统一化

startup.cs 中 ConfigureServices 下进行配置

services.Configure(options => {
    options.InvalidModelStateResponseFactory = actionContext =>
    {
        var a = actionContext.HttpContext.Response.StatusCode;

        var errors = actionContext.ModelState
        .Where(p=>p.Value.Errors.Count>0)
        .Select(p=>p.Value.Errors.First().ErrorMessage)
        .ToList();
        var str = string.Join("|",errors);

        var result = new BaseResultOutput()
        {
            Code = Enum.Base.ResultCode.Error,
            Message = $"{str}"
        };

        return new JsonResult(result);
    };
});

此时,接口返回的数据便会按照我们自定义的消息结构体进行返回

{
  "code": 1,
  "status": 0,
  "data": "",
  "message": "The Account field is required.|The Password field is required.",
  "time": "2021/4/15 23:44:50"
}