ASP.NET MVC 4 RC Web API ModelState Error for Optional URL Parameters That Are Null

I wanted to create a global valdiation attribute for my web API. So I followed the tutorial and got the following attribute:

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid)
        {
            return;
        }

        var errors = new List<KeyValuePair<string, string>>();
        foreach (var key in actionContext.ModelState.Keys.Where(key =>
            actionContext.ModelState[key].Errors.Any()))
        {
            errors.AddRange(actionContext.ModelState[key].Errors
                  .Select(er => new KeyValuePair<string, string>(key, er.ErrorMessage)));
        }

        actionContext.Response =
            actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
    }
}

Then I added it to the global fiters in Global.asax:

configuration.Filters.Add(new ValidationActionFilter());

It works great with most of my actions, but not as expected, with actions that have optional and null query parameters.

For instance:

I created a route:

routes.MapHttpRoute(
    name: "Optional parameters route", 
    routeTemplate: "api/{controller}", 
    defaults: new { skip = UrlParameter.Optional, take = UrlParameter.Optional });

And the action is in mine ProductsController:

public HttpResponseMessage GetAllProducts(int? skip, int? take)
{
    var products = this._productService.GetProducts(skip, take, MaxTake);

    return this.Request.CreateResponse(HttpStatusCode.OK, this._backwardMapper.Map(products));
}

Now, when I request this url:, http://locahost/api/productsI get a response with a 403 status code and the following content:

[
{
    "Key": "skip.Nullable`1",
    "Value": "A value is required but was not present in the request."
},
{
    "Key": "take.Nullable`1",
    "Value": "A value is required but was not present in the request."
}
]

I believe that this should not look like a validation error, since these parameters are optional and are reset to zero.

- ?

+5
2

, Web API MVC, RouteParameter -API UrlParameter MVC

routes.MapHttpRoute(
    name: "Optional parameters route", 
    routeTemplate: "api/{controller}", 
    defaults: new { skip = RouteParameter.Optional, take = RouteParameter.Optional }
    );

:

, , . :

routes.MapHttpRoute(
    name: "Optional parameters route", 
    routeTemplate: "api/{controller}"
    );
+2

/ GET.

public class ModelValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid && actionContext.Request.Method != HttpMethod.Get)
            { ...
+4

All Articles