Sup*_*Bob 9 c# validation model-view-controller model asp.net-core
我的所有模型在到达端点之前都会自动验证,如果某种形式的验证失败,则返回适当的错误。
我记得在 ASP.NET Core 2.2 中,我们需要手动调用ModelState.IsValid以确保对象已通过验证检查,但在最新的 ASP.NET Core 3.0 中,情况似乎并非如此,而且我无处包括/为存在此行为显式配置任何服务。
有人可以对此事有所了解,也许可以链接他们提到此更改的相关来源吗?
编辑:是由于[ApiController]属性吗?请参阅:https : //docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1#automatic-http-400-responses
谢谢!
cit*_*nas 14
使用该[ApiController]属性时,您无需在每个方法中检查 ModelState.IsValid,因为会自动返回 400 状态代码以及验证失败的字段的名称,请参阅https://docs.microsoft.com/en-us /aspnet/core/mvc/models/validation?view=aspnetcore-3.1
您甚至可以修改 400 状态代码的外观。这篇博客文章应该可以帮助您入门:https : //coderethinked.com/customizing-automatic-http-400-error-response-in-asp-net-core-web-apis/
添加此依赖项:
services.AddMvc.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var problems = new CustomBadRequest(context);
return new BadRequestObjectResult(problems);
};
});
Run Code Online (Sandbox Code Playgroud)
您的自定义错误请求类可能如下所示。如果您想包含有关错误的其他信息,例如错误严重性、警告等,请创建一个 YourErrorClass 类。
public class CustomBadRequest
{
[JsonProperty("httpstatuscode")]
public string HttpStatusCode { get; set; }
[JsonProperty("errors")]
public List<YourErrorClass> Errors { get; set; } = new List<YourErrorClass>();
public CustomBadRequest(ActionContext context)
{
this.HttpStatusCode = "400";
this.Errors = new List<YourErrorClass>();
this.ConstructErrorMessages(context);
}
private void ConstructErrorMessages(ActionContext context)
{
foreach (var keyModelStatePair in context.ModelState)
{
var key = keyModelStatePair.Key;
var errors = keyModelStatePair.Value.Errors;
if (errors != null && errors.Count > 0)
{
foreach (var error in errors)
{
Errors.Add(new YourErrorClass()
{
ErrorMessage = error.ErrorMessage
// add additional information, if you like
});
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4034 次 |
| 最近记录: |