Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the same route with different parameter types?

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.

like image 675
OrbitalFriendshipCannon Avatar asked Jun 04 '15 10:06

OrbitalFriendshipCannon


People also ask

Can we have multiple routes in MVC?

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.

What are Route constraints?

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.

How many routes can be defined in the MVC application?

there are no limits in creating routes. You can create as many route as you want in your RouteConfig. cs file.


Video Answer


1 Answers

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 ?

like image 113
Rohit Sonaje Avatar answered Oct 05 '22 22:10

Rohit Sonaje