简体   繁体   English

如果 controller 方法中的参数构造在 .NET Core 3.1 中失败,如何更改 http 响应错误消息?

[英]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.

相关问题 如何测试在 .NET Core 3.1 中的响应内容中不返回数据的控制器 POST 方法? - How to test a controller POST method which returns no data in response content in .NET Core 3.1? .NET Core 3.1 API 方法中的 GZip 响应 - GZip response in API method with .NET Core 3.1 ASP.Net Core 3.1:控制器方法总是从 HttpPost 调用接收 NULL 参数 - ASP.Net Core 3.1: Controller method always recieves NULL parameter from HttpPost call 如何更改 .NET Core 3.1 的语言环境? - How to change Locale of .NET Core 3.1? 如何在 ASP NET Core 3.1 中的任何 controller 的每种方法中检查/重定向? - How to check/redirect in every method of any controller in ASP NET Core 3.1? .Net core controller方法的动态参数 - Dynamic parameter for .Net core controller method 如何在asp.net core(Kestrel)中记录http请求消息(非正文)和响应消息(非正文) - how to log http request message(not body) and response message(not body) in asp.net core(Kestrel) HTTP 错误 405 | [HttpPost] ASP.NET MVC 核心 3.1 - HTTP ERROR 405 | [HttpPost] ASP.NET MVC Core 3.1 如何在 .net core 3.1 中删除一个 Controller Action 的 CORS 限制 - How to remove CORS restriction for one Controller Action in .net core 3.1 如何在 .Net Core 3.1 Web API 控制器中获取声明? - How to get claims in .Net Core 3.1 Web API Controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM