1

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.

1
  • Change the model property to a string. My betting is the result would then be what you would expect. Commented Mar 22, 2013 at 22:14

1 Answer 1

2

It seems the answer is as simple as making the model properties nullable. This way they will pass JSON validation and data model validation based on data annotations will kick in:

public class SimplePoint
{
    [Required(ErrorMessage="MonitorKey is a required data field of SimplePoint.")]
    public Guid? MonitorKey { get; set; }

    [Required]
    public int? Data { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you cannot have a required attribute on a non-nullable property. A) it doesn't make sense since null = not present and this condition could never be met and B) JSON will attempt to parse the string into a GUID before attempting validation, which will fail if there is no value and the property is not nullable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.