根据这篇文章ASP.NET - Model Validation,我应该很好地描述模型绑定过程中遇到的错误,这些错误是基于模型中的数据注释。那么,在验证工作的同时,它不会给我提供很好的错误,而是提供JSON解析错误。Web API模型验证问题
这里是我的模型:
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 - Issue - 在Global.asax中的Application_Start这个代码exixts方法:
GlobalConfiguration.Configuration.Services.RemoveAll(
typeof (System.Web.Http.Validation.ModelValidatorProvider),
v => v is InvalidModelValidatorProvider);
这是我的要求使用小提琴手:
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,我看不到由Model验证器拾取的ErrorMessage。
将模型属性更改为字符串。我的投注结果就是你期望的结果。 – LiverpoolsNumber9 2013-03-22 22:14:11