26

How can I make a method with two parameters using ASP.NET Web Api?

So that I can call it like localhost/controller/param1/param2

3 Answers 3

57

You can also call the url with specific params names in the querystring:

/api/actions?param1=5&param2=1/1/2000

Then the controller method would be:

GetByParams(int param1, DateTime param2)
Sign up to request clarification or add additional context in comments.

3 Comments

This is the better answer. The accepted answer works, but the URL doesn't make as much sense. /id/name works out to something like this for a URL: mysite/api/DoStuff/12345/Vince. That doesn't make much sense. Like "Vince" is some item in the "12345" category. mysite/api/users/Vince makes a lot more sense or mysite/api/users?name=Vince&id=12345
Great Answer. Exactly what i was wanting.
Coul you provide a link to the official details about the GetByParams method? I have not been able to locate it. I have tested it, though, and it works as you described.
7

Just change or add route in global.asax

routes.MapHttpRoute(name: "DefaultApi1", routeTemplate: "api/{controller}/{id}/{name}", Defaults: new{} );

Comments

7

I think the easiest way is to simply use AttributeRouting.

[Route("api/YOURCONTROLLER/{paramOne}/{paramTwo}")]
public string Get(int paramOne, int paramTwo) {
    return "The [Route] with multiple params worked";
}

The {} names need to match your parameters.

Attribute Routing in ASP.NET Web API 2

1 Comment

Man I used this 1000 times, and always thought It was sort of a "hack" and there is better way. Seems like this is actually best practice..

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.