Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Web Api Get Not Mapping QueryString To Strongly Typed Parameter

The parameter request is always null using Web API. Am I missing something with using a strongly typed object as a parameter instead of simple types as the parameters.

Url

http://localhost:2222/api/v1/divisions?EventId=30

Controller Action

public virtual ApiDivisionsResponse Get(ApiDivisionsRequest request)
        {
            return _apiDivisionsService.GetDivisions(request);
        }

Object

public class ApiDivisionsRequest : ApiAuthorizedRequest
    {
        public ApiDivisionsRequest()
        {
            Page = 1;
            PageSize = 10;
        }

        public int EventId { get; set; }
        public int PageSize { get; set; }
        public int Page { get; set; }
        public string[] Includes { get; set; }
    }  
like image 620
Mike Flynn Avatar asked Sep 25 '12 19:09

Mike Flynn


1 Answers

I very strongly invite you to read the following article to better understand how parameter binding works in the Web API. After reading it you will understand that by default the Web API binds query string parameters to primitive types and request body content to complex types.

So if you need to bind query string parameters to complex types you will need to override this default behavior by decorating your parameter with the [FromUri] parameter:

public virtual ApiDivisionsResponse  Get([FromUri] ApiDivisionsRequest request)
{
    ...
}

And yeah, I agree with you - that's a hell of a mess - model binding was so easy in plain ASP.NET MVC and they created a nightmare in the Web API. But once you know how it works you will avoid the gotchas.

like image 115
Darin Dimitrov Avatar answered Oct 16 '22 14:10

Darin Dimitrov