在碰到端点之前,我的所有模型都会自动进行验证,如果某种形式的验证失败,则会返回相应的错误。
我记得在ASP.NET Core 2.2中,我们需要手动调用ModelState.IsValid
以确保对象已通过验证检查,但是对于最新的ASP.NET Core 3.0,情况似乎并非如此,而且我在哪里都没有/明确配置任何服务以使此行为存在。
有人可以对此事发表一些看法,或者可以在他们提到此更改的地方链接相关消息来源吗?
编辑:是由于[ApiController]
属性?请参阅:https : //docs.microsoft.com/zh-cn/aspnet/core/web-api/?view=aspnetcore-3.1#automatic-http-400-responses
谢谢!
使用该[ApiController]
属性时,无需在每个方法中检查ModelState.IsValid,因为会自动返回400状态代码以及验证失败的字段的名称,请参阅https://docs.microsoft.com/zh-cn /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);
};
});
您的自定义错误请求类可能如下所示。如果要包含有关错误的其他信息,例如错误严重性,警告等,请创建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
});
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句