25

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; }
    }  
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

1 Answers1

51

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 5
    Created a nightmare isn't the half of it. Seems that just about everything the ASP.Net crew touches becomes the poster child for "The Stupid, It Burns!". AjaxControlToolkit, and now this abortion... – jerhewet Sep 12 '14 at 14:30
  • 2
    @jerhewet Realize that there were driving factors at the time of creating some of these ridiculous web forms components. Customer demand and Microsoft was competing with offerings from the Java world. This great ecosystem that we have today might not have existed if it wasn't for the stepping stones of ASP.NET Webforms and others. – The Muffin Man Mar 22 '17 at 22:24