美文网首页
.net web api json参数错误的json格式和返回结

.net web api json参数错误的json格式和返回结

作者: 吉凶以情迁 | 来源:发表于2022-09-06 08:45 被阅读0次

    经过测试发现 要获取 详细信息需要通过
    Microsoft.AspNetCore.Mvc.ValidationProblemDetails(context.ModelState)解析,

    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

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

    相关文章

      网友评论

          本文标题:.net web api json参数错误的json格式和返回结

          本文链接:https://www.haomeiwen.com/subject/ztwpgrtx.html