Web API模型验证问题
本文关键字:问题 验证 模型 API Web | 更新日期: 2023-09-27 18:05:28
根据本文ASP。. NET -模型验证,我应该得到一个很好的描述在模型中基于数据注释的模型绑定过程中遇到的错误。好吧,虽然验证正在工作,但它并没有为我提供很好的错误,而是JSON解析错误。
这是我的模型:public class SimplePoint
{
[Required(ErrorMessage="MonitorKey is a required data field of SimplePoint.")]
public Guid MonitorKey { get; set; }
public int Data { get; set; }
}
这是我的验证过滤器:
public class ModelValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest,
actionContext.ModelState);
}
}
}
我不得不删除InvalidModelValidationProvider在这篇文章中确定:ASP。NET -问题-此代码在全局中存在。asax Application_Start方法:
GlobalConfiguration.Configuration.Services.RemoveAll(
typeof (System.Web.Http.Validation.ModelValidatorProvider),
v => v is InvalidModelValidatorProvider);
这是我使用Fiddler的请求:
POST http://localhost:63518/api/simplepoint HTTP/1.1
User-Agent: Fiddler
Host: localhost:63518
Content-Length: 28
Content-Type: application/json; charset=utf-8
{"MonitorKey":"","data":123}
这里是控制器的响应:
HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcTG9jYWwgVmlzdWFsIFN0dWRpbyBwcm9qZWN0c1xKaXREYXNoYm9hcmRcSml0RGFzaGJvYXJkLldlYi5Nb25pdG9 ySG9zdFxhcGlcc2ltcGxlcG9pbnQ=?=
X-Powered-By: ASP.NET
Date: Fri, 22 Mar 2013 21:55:35 GMT
Content-Length: 165
{"Message":"The request is invalid.","ModelState":{"data.MonitorKey":["Error converting value '"'" to type 'System.Guid'. Path 'MonitorKey', line 1, position 16."]}}
为什么我没有得到数据注释中标识的错误消息(即:"MonitorKey是SimplePoint的必需数据字段")?在我的验证过滤器中分析ModelState,我没有看到ErrorMessage被模型验证器拾取。
似乎答案就像使模型属性为空一样简单。通过这种方式,它们将通过JSON验证,并且基于数据注释的数据模型验证将开始:
public class SimplePoint
{
[Required(ErrorMessage="MonitorKey is a required data field of SimplePoint.")]
public Guid? MonitorKey { get; set; }
[Required]
public int? Data { get; set; }
}