1

While working with Web API, came across a situation when calling a GET method from client.

//This didn't worked
public IEnumerable<type> Get(string mode)
{
    //Code
}

//This worked
public IEnumerable<type> Get(string id)
{
    //Code
}

Just change in the name of parameter make my call successful. I am using default route.

What's the problem with that method. And what if I want a GET method with multiple parameters. For eg:

pulbic string GET(string department, string location)
{
    //Code here
}

1 Answer 1

1

I would need to see the calling code and route config to be certain but my guess is that you may be using restful routing. Switch to using a query string with named parameters and all of your methods should work:

http://api/yourcontroller?id=something

http://api/yourcontroller?mode=somethingelse

http://api/yourcontroller?department=adepartment&location=alocation

The default route template configuration understands id. You may see this in the App_Start folder in the WebApiConfig static class method Register.

This is the default:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Based on this default, the action method parameter (id) is set as part of the route data which is why the second action method in the controller code you listed above would work. You would not be able to use template routing or attribute routing to set the value in get for multiple single paramter get methods in the same controller because it would create an ambiguous condition.

You may want to review the details on parameter binding at the following link. Binding can be a little tricky at times in Web Api 2 because the model binders and formatters included by default do a lot of work behind the scenes.

http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

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

1 Comment

Thanx BIll, It really sounds an explanation for the problem. The link is really helpful.

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.