Typically, you have this standard piece of routing configuration:
Which does the job of matching “/” to HcomeController‘s Index action.
The reason it works is simple, the id parameter is obviously optional, the action parameter if not present will be set to Index, so, this routing will match “/home/index/”, and similarly will match “/home/”. But the controller also will be set to HcomeController if it’s not present (the Controller suffix is a convention in class name), so, this matches “/home/” and “/”.
Using Explicit Route
Until here, there is no point of this blog post. So, lets say for whatever reason you are using other routing rules, because your desired routes don’t follow this very convention or because you don’t want to couple public URL structure to internal class names or have another reason to make your routes explicit, how do you set a route for the homepage or website root “~/” URL in this case?
One possible case is to have this exact default route still there, but make sure it’s at the very end of your route registrations, after all other have been registered, so, it has the least priority in matching. The drawback is that it’s still more generic than its purpose, technically allows using it for other actions than the one handling the homepage, and every request to homepage will go through all routes tried first (which is usually not a very slow thing to be honest).
So, a nicer way is to be able to have an explicit homepage route. Maybe even one that can be put on the top of route registrations to make the request to our homepage the fastest ever (although again, it’s not a big deal or difference, but nice to have). Turns out the way is VERY easy, just set the URL to an empty string “”.
Yeah, that’s it (the “name” doesn’t matter BTW, and you can obviously use whatever controller/action too). Even if you are using the default routes, you can combine it with them, and put it before them too. Empty string will NOT match any URL that is not empty (you can argue all other requests are matched against this, but comparing a string against an empty one must be VERY quick, right?)
Note that this all is application specific, so, the root here is website root “~/” not server root, so, this should still work if your website is hosted under some virtual directory too.
Not that it matters a lot, but thought some of you would be interested :).
How did I learn that?
As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.
It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2+, ASP.NET (4.x/MVC5 and Core), and other fullstack developer goodies.
Take it for a test ride, and you may unsubscribe any time.
You might also want to support me by checking these out [Thanks]: