I have an Api controller with two different actions that take different parameter types.
// GET: users/sample%40email.com
[Route("users/{emailAddress}")]
public IHttpActionResult GetUser(string emailAddress)
// GET: users/1D8F6B90-9BD9-4CDD-BABB-372242AD9960
[Route("users/{reference}")]
public IHttpActionResult GetUserByReference(Guid reference)
Problem is multiple actions are found matching when I make a request to either. Looking at other answers I thought I needed to setup routes in the WebApiConfig like so...
config.Routes.MapHttpRoute(
name: "apiEmail",
routeTemplate: "api/{controller}/{action}/{email}"
);
config.Routes.MapHttpRoute(
name: "apiReference",
routeTemplate: "api/{controller}/{action}/{reference}"
);
What do I need to do so that each action is called based on the parameter type I pass in?
I'm very new to Web.Api any additional explanation text would be appreciated.
Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.
Routing constraints lets you restrict how the parameters in the route template are matched. It helps to filter out the input parameter and action method can accept. Routing constraints let you restrict how the parameters in the route template are matched.
there are no limits in creating routes. You can create as many route as you want in your RouteConfig. cs file.
You do like below method declaration with attribute routing enabled: //declare method with guid 1st
// GET: users/1D8F6B90-9BD9-4CDD-BABB-372242AD9960
[Route("users/{reference:guid}")]
public IHttpActionResult GetUserByReference(Guid reference)
and declare other method like below
// GET: users/sample%40email.com
[Route("users/{emailAddress}")]
public IHttpActionResult GetUser(string emailAddress)
Please let me know, is this work for you ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With