How to use the same route with different parameter types?

和自甴很熟 提交于 2019-12-23 12:49:28

问题


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.


回答1:


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 ?



来源:https://stackoverflow.com/questions/30641012/how-to-use-the-same-route-with-different-parameter-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!