ASP.NET MVC 5 dynamic controller routes

2019-08-10 05:54发布

问题:

I'm having a challenge figuring out the best way to define my hierarchical based routes dynamically.

I'm looking to achieve database driven links similar to the below:

/Illinois/
/Illinois/Chicago/
/Illinois/Chicago/Id
/California/
/California/Los-Angeles/
/California/Los-Angeles/Id
/New-York/
/New-York/New-York-City/
/New-York/New-York-City/Id

And so on, I don't want to have to define a controller for each state, but I'm not 100% against if if it's "the right way".

回答1:

You can create a controller like HomeController and use route attributes on the top of this controller and related action to hide the route url and call your locations and ids in route like this:

[RoutePrefix("")]
public class HomeController : Controller
{
    Route("{state?}/{city?}/{id?}")
    public ActionResult Index(string state, string city, int id)
    {
        //your codes
        return View();
    }
}