0
点赞
收藏
分享

微信扫一扫

.net web api json参数错误的json格式和返回结果响应码定制


经过测试发现 要获取 详细信息需要通过​​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,




.net web api json参数错误的json格式和返回结果响应码定制_json


image.png


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

举报

相关推荐

0 条评论