简体   繁体   中英

Change routeconfig

In the RouteConfig-file I see :

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Which then maps in my controller to

public Person Get(int id)
{
    return _personService.GetPersoonByInszNumber("11111111111");
}

Now I would like to change this so it maps to the following :

public Person Get(string inszNumber)
{
    return _personService.GetPersoonByInszNumber(inszNumber);
}

How can I do this?

It can be done using attrubute routing :

[Route("Persons/Get/{id:int}")]
public Person Get(int id)
{
    ....
}

[Route("Persons/Get/{inszNumber}")]
public Person Get(string inszNumber)
{
    ....
}

Just add appropriate attributes (here I'm supposing your controller name is PersonsController . In other case change it appropriately) to your actions.

Also make sure you have this line of code in RegisterRoutes method just before default route declaration:

routes.MapMvcAttributeRoutes();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM