I am working on a small ASP.NET MVC project at the moment. The project was released a few month ago. But changes should be implemented for usability and SEO reasons now. I decided to use attribute routing to create clean URLs.
At the moment a product page is called by:
hostname.tld/Controller/GetArticle/1234
I defined a new Route like this:
[Route("Shop/Article/{id:int}/{title?}", Name = "GetArticle", Order = 0)]
public ActionResult GetArticle(int id, string title = null) {
// Logic
}
Everything works fine, but because of backwards compatibility and SEO reasons, the old route should be still available. And redirected with HTTP status code 301 to the new URL.
I’ve heard that it is possible to assign multiple routes to one action, like this:
[Route("Shop/Article/{id:int}/{title?}", Name = "GetArticle", Order = 0)]
[Route("Controller/GetArticle/{id:int}", Name = "GetArticle_Old", Order = 1)]
public ActionResult GetArticle(int id, string title = null) {
// Logic
}
But I have no idea if this is a good solution or how to determine which route was called?
3
Answers
You can look at
ControllerContext.RouteData
to figure out which route they used when using multiple routes for one action.I wanted to be able to pass different views based on the request but they all basically used the same process and didn’t want to make an action for each. The prior answer doesn’t seem to work any more so here is what I came up with. This is .Net Core 2.2.
This will allow you to put your individual views as the name of the routes and use them to set the view.
This works for me.