[英]How to change http response error message if parameter construction in controller method fails in .NET Core 3.1?
I have a controller method which takes a SignUpDTO object as a parameter.我有一个 controller 方法,它将 SignUpDTO object 作为参数。 Here is SignUpDTO class code, and the header of mentioned controller method:
这是SignUpDTO class代码,以及提到的controller方法的header:
[HttpPost("register")]
public async Task<ActionResult<UserDTO>> SignUpAsync([FromBody] SignUpDTO signUpData)
...
public class SignUpDTO
{
[Required]
[StringLength(100, MinimumLength = 3)]
public string Username { get; set; }
[Required]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$")]
public string Password { get; set; }
[Required]
[RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$")]
public string MailAddress { get; set; }
}
Properties are decorated with some attributes which validates data.属性装饰有一些验证数据的属性。 My problem is, if some invalid data comes with http request, the execution of the method does not even start.
我的问题是,如果 http 请求附带一些无效数据,则该方法的执行甚至没有开始。 Here i include exemplary response sent by my api:
这里我包括我的 api 发送的示例性响应:
{
"errors": {
"MailAddress": [
"The field MailAddress must match the regular expression '^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$'."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|fcfb9908-4cd92abdc9dea235."
}
I would like to change JSON object sent with response, and send just simple message to be consistent with the other methods.我想更改随响应发送的 JSON object,并发送简单的消息以与其他方法保持一致。 The response should look like:
响应应如下所示:
{
"message": "Improper mail address!"
}
Is it possible to change default response if construction of the object fails?如果 object 的构造失败,是否可以更改默认响应? If not how i can solve my problem?
如果不是我怎么能解决我的问题? Thank you
谢谢
All of the attributes which extend ValidationAttribute
allow you to provide a custom error message by setting the ErrorMessage
property ( MSDN link ):扩展
ValidationAttribute
的所有属性都允许您通过设置ErrorMessage
属性( MSDN 链接)来提供自定义错误消息:
[RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Improper mail address!")]
You can also change your return type to Task<IActionResult>
this return type supports any possible object see documentation :您还可以将返回类型更改为
Task<IActionResult>
此返回类型支持任何可能的 object 参见文档:
[HttpPost("register")]
public async Task<IActionResult> SignUpAsync([FromBody] SignUpDTO signUpData)
{
if (signUpData == null || <any other validation>)
{
return BadRequest(<your response object with message only>);
}
/// your application code
return Ok(<your UserDTO>);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.