According to this article ASP.NET - Model Validation, I should be getting a nice description of errors encountered during model binding based on data annotations in my model. Well, while the validation is working, it is not providing me with nice errors but rather with JSON parsing errors.
Here is my model:
public class SimplePoint
{
[Required(ErrorMessage="MonitorKey is a required data field of SimplePoint.")]
public Guid MonitorKey { get; set; }
public int Data { get; set; }
}
Here is my validation filter:
public class ModelValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest,
actionContext.ModelState);
}
}
}
I had to remove InvalidModelValidationProvider as identified in this post: ASP.NET - Issue - this code exixts in Global.asax Application_Start method:
GlobalConfiguration.Configuration.Services.RemoveAll(
typeof (System.Web.Http.Validation.ModelValidatorProvider),
v => v is InvalidModelValidatorProvider);
Here is my request using 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}
And here is my response from my controller:
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."]}}
Why am I not getting an error message identified in my data annotation (i.e. "MonitorKey is a required data field of SimplePoint")? Analyzing ModelState in my validation filter, I don't see the ErrorMessage being picked up by the Model validator.