Heinrich
Heinrich

Reputation: 1761

Passing a parameter on a Web API Get method

This is my api controller method to get a list of items filtered by a user id.

public IEnumerable<MyItemListItemDTO> Get(int userId)

When calling the method from the client why won't /MyItems/Get/11 work and /MyItems/Get?userId=11 does?

Upvotes: 0

Views: 199

Answers (1)

user1620696
user1620696

Reputation: 11375

Because on the parametrized URL the name of the parameter is id rather than userId. Model binder checks the name of the parameter to do the binding. Look on the routes definition and you'll see that.

What I mean, basically is that on the RouteConfig.cs file you have as the default route the following:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

Look that the URL is controller/action/id and the name of the last parameter is id. So, in some action, to receive that piece of the URL you must match the name of the parameter.

Upvotes: 1

Related Questions