[英]Model state returns right away .Net Core 5
I have a custom validation attribute我有一个自定义验证属性
public class IsUsernameAcceptableAttr:ValidationAttribute
{
protected override ValidationResult IsValid(object username, ValidationContext validationContext)
{
var _username = username.ToString();
if (_username.Length<4)
return new ValidationResult("Username must be at least 4 characters.");
return ValidationResult.Success;
}
}
in my DTO class I have在我的 DTO class 我有
public class UserAccountInformationDTO
{
[IsUsernameAcceptableAttr]
public string Username { get; set; }
}
In action method I got在行动方法我得到
public IActionResult UpdateAccountInformationstring(UserAccountInformationDTO accountInfo)
{
var ms = ModelState.IsValid;
return Ok();
}
The issue is when model state hits an error it send a response back in errors
as JSON response.问题是当 model state 遇到错误时,它会以 JSON 响应的形式返回
errors
响应。 I never get to do anything in the controller or alter the response to a format that i want.我从来没有在 controller 中做任何事情,或者将响应更改为我想要的格式。 What else can i do?
我还可以做些什么?
You need to specify the source of the parameters您需要指定参数的来源
https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0#binding-source-parameter-inference https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0#binding-source-parameter-inference
Update:更新:
Add the following codes to your startup ConfigureServices:将以下代码添加到您的启动 ConfigureServices:
services.Configure<ApiBehaviorOptions>(apiBehaviorOptions => {
apiBehaviorOptions.SuppressModelStateInvalidFilter = true;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.