[英]Model Validation in ASP.NET Web API 2 Controller and return different Status Codes on different validation fails
HERE is a good but basic article for Model Validation in ASP.NET Web API 2 Controller. 这里是一篇不错的文章,但是很基本,它介绍了ASP.NET Web API 2 Controller中的模型验证。 But it does not discuss how could we send custom messages with custom HttpStatusCodes . 但是它没有讨论如何使用自定义HttpStatusCodes发送自定义消息 。
For example, I want to return status code as 499 and message as ' Name Required ' when 'Name' field not provided 例如,当未提供“名称”字段时,我想返回状态码为499 ,消息为“ 需要名称”
I want my HTTP response to look something like 我希望我的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**"
]
}
}
I want custom status code and custom message as shown in provided response. 我想要自定义状态代码和自定义消息,如提供的响应所示。
How could I achieve this? 我怎样才能做到这一点?
This is unlikely to be a good idea, http status codes have specific meanings and although 499 isn't a standard code nginx does use it and you'll be limited to the gaps that are currently in the specs. 这不太可能是一个好主意,http状态代码具有特定的含义,尽管499不是nginx会使用的标准代码,但是您将受到规范中当前的空白的限制。 Just return a custom code in your response body instead. 只需在响应正文中返回自定义代码即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.