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; }
    }  

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

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.