Search code examples
asp.net-web-api2restful-urlattributerouting

Converting API from REST-like routing to named parameters


I have created an API that looks for parameters as such ...

http://server/api/contollerName/param1/param2/param3

for this pattern I used the following method attribute:

[Route("api/myController/{param1}/{param2}/{param3}")]
[HttpGet]
public IHttpActionResult myMethod(int param1, int param2, int param3)
{
  // Method implementation goes here
}

However the person who will be utilizing the API (the UI developer) would prefer to have the API setup as this ...

http://server/api/controllerName?param1=value&param2=value&param3=value

Am I correct in thinking that all I need to do is remove the attribute to my method and the Web Api routing engine will choose the correct method based on the parameter names? Is there a way I could modify the route to explicitly define the method and parameters like I have originally done? I like having the route specified so there is no ambiguity as to which method will be executed.


Solution

  • You are correct in thinking that all you need to do is to remove the attribute to your method. You would not be able to define a route template of the format

    http://server/api/controllerName?param1=value&param2=value&param3=value

    because ASP.Net Web API2 routing template does not allow to contain a "?" character in the route template. The closest you can get to is

    http://server/api/controllerName/MethodName/param1={param1},param2={param2}

    Also notice that if you have & in the routing template, ASP.NET will throw an error that dangerous Request.Path value was detected, when you make the request to hit that API. This can be resolved though by referring to this SO Question