ASP.NET Web API 2 控制器和 return 中的模型验证不同验证失败的不同状态代码

Model Validation in ASP.NET Web API 2 Controller and return different Status Codes on different validation fails

HERE 是 ASP.NET Web API 2 Controller 中模型验证的一篇很好但基础的文章。但它没有讨论我们如何使用 custom HttpStatusCodes.

发送 custom messages

例如, 当未提供 'Name' 字段时,我想 return 状态代码为 499 并且消息为 'Name Required' 15=]

我希望我的 HTTP 响应看起来像

HTTP/1.1 **499** 
Bad Request  Content-Type: application/json; charset=utf-8 
Date: Tue, 16 Jul 2013 21:02:29 GMT  
Content-Length: 331

{   
    "Message": "The request is invalid. *Please check*.",
    "ModelState": {
      "product": [
        "Required property 'Name' not found in JSON. Path '', line 1, position 17."
    ],
     "product.Name": [
      "**Name Required**"
    ]
   }
 }

我想要自定义状态代码和自定义消息,如提供的响应中所示。

我怎样才能做到这一点?

这不太可能是个好主意,http 状态代码具有特定含义,虽然 499 不是标准代码,但 nginx 确实使用它,您将被限制在 当前的空白 在规格中。只需 return 响应正文中的自定义代码即可。