给出以下控制器:
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// POST api/values
[HttpPost]
public ActionResult<string> Post([FromBody] Model req)
{
return $"Your name is {req.Name}";
}
}
public class Model
{
[Required] public string Name { get; set; }
}
}
如果我发布一个空的正文{}
,则响应为:
{
"errors": {
"Name": [
"The Name field is required."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "80000002-0002-ff00-b63f-84710c7967bb"
}
我想更改此响应,因此将错误消息自动传递给用户变得更加容易。所以我希望它看起来像这样:
{
"error": 999,
"message": "Field 'name' is required."
}
我试图像这样扩展RequiredAttribute
类:
public class MyRequiredAttribute : RequiredAttribute
{
public MyRequiredAttribute()
{
ErrorMessage = "{0} is required";
}
}
可悲的是,它只能更改集合中返回的字符串,就像这样
{
"errors": {
"Name": [
"Name is required"
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "80000006-0000-ff00-b63f-84710c7967bb"
}
答案 0 :(得分:0)
在使用应用了ApiController属性的控制器时,ASP.NET Core通过返回一个以ModelState作为响应主体的400 Bad Request来自动处理模型验证错误。它与Automatic HTTP 400 responses有关。您可以自定义BadRequest响应,如下所示:
services.AddMvc()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = actionContext =>
{
var modelState = actionContext.ModelState;
return new BadRequestObjectResult(FormatOutput(modelState));
};
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
根据自己的想法自定义FormatOutput
方法。
public List<Base> FormatOutput(ModelStateDictionary input)
{
List<Base> baseResult = new List<Base>();
foreach (var modelState in input.Values)
{
foreach (ModelError error in modelState.Errors)
{
Base basedata = new Base();
basedata.Error = StatusCodes.Status400BadRequest;
basedata.Message =error.ErrorMessage;
baseResult.Add(basedata);
}
}
return baseResult;
}
public class Base
{
public int Error { get; set; }
public string Message { get; set; }
}
答案 1 :(得分:-1)
尝试将此代码添加到[Requried]批注下方
[StringLength(150, ErrorMessage = "Name length can't be less than 1 or greater than 150 characters.", MinimumLength = 1)]
希望这对您有帮助...