在ASP.NET Core中,什么类用于模型验证错误响应? [英] In ASP.NET Core, what class is used for model validation error responses?
问题描述
在我的ASP.NET Core Web API中,我正在使用数据注释进行模型验证.这是一个具有这些注释的类:
In my ASP.NET Core web API, I am using data annotations for model validation. Here is one class that has these annotations:
class CreateUserRequest {
[Required, RegularExpression("[a-zA-Z0-9\-_]+")]
public string Name { get; set; }
[Required, StringLength(20, MinimumLength = 6)]
public string Password { get; set; }
}
如果客户端尝试使用太短的密码创建用户,我将得到以下响应正文:
If a client tries to create a user with a password that is too short, I get this response body:
{
"errors": {
"password":[
"The field password must be a string with a minimum length of 6 and a maximum length of 20."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId":"|a301aaae-43dd49e731beb073."
}
我希望从API返回的所有错误都具有一致的结构,以使客户端更容易处理错误.在其他错误情况下,是否可以使用一个类来获取相同的结构?
I would like all errors returned from the API to have a consistent structure, to make it easier for clients to handle errors. Is there a class I can use to get this same structure for other error cases?
推荐答案
您正在寻找 ValidationProblemDetails
.
You are looking for ValidationProblemDetails
.
如果要在响应中返回其他属性,则可以简单地扩展上述类并添加所需的任何内容,然后调用
If you want to return additional properties on your response, you can simply extend the abovementioned class and add whatever you need, then call ControllerBase.ValidationProblem(ValidationProblemDetails)
with an instance of your class instead of using the standard call to BadRequest()
.
这篇关于在ASP.NET Core中,什么类用于模型验证错误响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!