Reputation: 709
Being new and transitioning from ruby on rails. I would like to understand how to change the default routes to use custom routing.
For eg the current routes in my WebApiConfig.cs
is as follows:
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional}
So the URL GET api that I have configured in my controller is:
https://localhost:44300/api/Controller?type=FirstType
The corresponding method defined in my controller is:
public HttpResponseMessage GetControllerByType(string type)
What are the changes to be made to execute the same as above when calling the WEB api using the URL:
https://localhost:44300/api/Controller/FirstType
Upvotes: 3
Views: 5493
Reputation: 7097
Assuming that you're using WebAPI 2 you can create custom routes using attributes on your actions within the controllers.
Add the following to the Register method of your WebApiConfig.cs:
config.MapHttpAttributeRoutes();
The above should be added BEFORE the default routing configuration that you already posted above.
Then within your controllers you can use annotations to describe routes:
[Route("controller/{type}")]
[HttpGet]
public HttpResponseMessage GetControllerByType(string type)
Values that are inside the brackets represent variables that are bound to the parameters of the method via their names.
You can also annotate classes themselves to have prefixes that apply to all methods within that controller:
[RoutePrefix("stuff")]
public class MyController : ApiController
{
[Route("myAction/{id}")] //route to this is via /stuff/myAction/{id}
[HttpGet]
public HttpResponseMessage MyMethod(string id)
{ ... }
}
The only 'gotcha' is that query strings should NOT be within the route template, those are represented by optional parameters (those with default values) in your method signature, which don't also have an optional annotation within the route template string. (ie: "myAction/{id:string?}"
must have a default value in the signature, but all other parameters that aren't id with default values can be assigned via a query string)
Anything that you do not provide a route template for using an annotation will fallback to using the default routes specified in the WebApiConfig, which is by default "/api/controller_name/action_name/"
Here's a great tutorial on all the custom routing using attributes that you can setup: Attribute Routing in ASP.NET WebAPI 2
Upvotes: 4