开启请求参数验证
[HttpPost]
public IActionResult Save([FromBody] User user)
{
string errorMessage = string.Empty;
if (!ModelState.IsValid)
{
foreach (var item in ModelState.Values)
{
foreach (var error in item.Errors)
{
errorMessage += error.ErrorMessage + "|";
}
}
}
if (!string.IsNullOrEmpty(errorMessage))
{
return BadRequest(errorMessage);
}
return Ok(user);
}
public class User
{
[Required(ErrorMessage = "账号不能为空")]
[StringLength(20)]
public string name { get; set; }
[Required()]
[StringLength(40)]
public string password { get; set; }
}
默认情况下并不会进入控制器返回errorMessage
而是报被框架内置捕获异常返回
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-7be909892e5fc14697682fffa2149fd3-d992eb52c5214b4f-00",
"errors": {
"name": [
"账号不能为空"
],
"password": [
"The password field is required."
]
}
}
如果我们要自己写验证判断的话
得修改Startup.cs的ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
// 关掉参数验证强制报错
options.SuppressModelStateInvalidFilter = true;
});
}
Heya i am for the first time here. I found this board and I find
It truly useful & it helped me out much. I hope to give
something back and help others like you helped me.