简书链接:netwebapijson参数错误的json格式和返回结果响应码定制
文章字数:190,阅读全文大约需要1分钟

经过测试发现 要获取 详细信息需要通过

1

builder.Services.AddControllers().ConfigureApiBehaviorOptions(setupAction => setupAction.InvalidModelStateResponseFactory = context =>
{
var problemDetail = new Microsoft.AspNetCore.Mvc.ValidationProblemDetails(context.ModelState)
{
Type = “无所谓”,
Title = “数据验证失败”,
Status = StatusCodes.Status200OK,
Detail = “请看详细说明”,
Instance = context.HttpContext.Request.Path
};/* var problemDetail = new Microsoft.AspNetCore.Mvc.ValidationProblemDetails(context.ModelState)
{
Type = “无所谓”,
Title = “数据验证失败”,
Status = StatusCodes.Status200OK,
Detail = “请看详细说明”,
Instance = context.HttpContext.Request.Path
};*/
int count=problemDetail.Errors.Count;

StringBuilder sb = new StringBuilder();
sb.Append("数据验证错误");

foreach (KeyValuePair<string, string[]> kv in problemDetail.Errors)

{

    StringBuilder s1 = new StringBuilder();
    for(int i=0;i< kv.Value.Length; i++)
    {
        s1.Append(kv.Value[i]+" ");

    }
    sb.Append($"参数:{kv.Key}错误,"+s1.ToString()+" ");
    //Console.WriteLine(kv.Key + kv.Value);

}
/*  for(int i = 0; i < count; i++)
  {
      problemDetail.Errors.Keys.for
      sb.Append(problemDetail.Errors[]);
  }*/
var result=new
{
    code = -1,
    Status = StatusCodes.Status200OK,
    msg = sb.ToString()
};
problemDetail.Extensions.Add("traceId", context.HttpContext.TraceIdentifier);
return new Microsoft.AspNetCore.Mvc.JsonResult(result);
/*    return new Microsoft.AspNetCore.Mvc.UnprocessableEntityObjectResult(problemDetail)
{
    ContentTypes = { "application/json" }
};*/

});

最后返回 jsonresult而不是UnprocessableEntityObjectResult否则结果代码并不是200,

![image.png](https://upload-images.jianshu.io/upload_images/2815884-628b2a4569d0116d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

下面地址实际上返回的是模拟默认的结果实现