Custom Routes For Your ASP.NET Core 3 Project

If you’re anything like me: when you wanted to find out more about ASP.NET you went to the internet.

May be you went to an online site that has training courses such as Udemy. Maybe you searched and found some tutorial pages. 

Me personally, I did both and after trying to follow some of these I found information that had gone out of date.

starting wit information I leant for Route

When I was trying to add a custom route to a page/method - I followed a course which told me to add it to RouteConfig.cs.

Configure the new route for my custom page and inputs in using MapRoute().

With a default .Net Core MVC build in Visual Studio 2019 this file was not in the project.

Examining the default C# files; in Startup.cs the endpoints are mapped using MapControllerRoute().

This worked well but did not give me the flexibility I was after. 

What I really wanted was to have a custom route defined for specific methods in my class that managed a single page.

For example: if I have a page called Movie. I wanted a page that maybe called Random. I then may want a page that displays Movie Titles or Authors.

Using the MapControllerRoute was starting to get a little clunky (using a technical term there) and did not give me the flexibility I needed. So, I decided to use Route in the controller.

Custom routes in the controller

Using this method of adding custom routes allows you to add a route per method for you controller.

So, as an example

Route(“Movie/Author/{name}”)]
Public IActionResult ByAuthor(string name) {...} </code></p>

The above allows us to go to a page named Http://our_site/Movie/Random

And also a page where we pass in a parameter Http://out_site/Movie/Author/Sean

In the above, Sean is passed is as a parameter and goes into the name parameter. We can then search our list of movies for the author name and output content found.

Both these methods would exist in the controller - which maybe named MovieController.cs

The best way to route in ASP.NET code

This, in my opinion, is the best way too route to pages in your ASP.NET code. Each method has its own custom route defined which includes any parameters. 

You don’t need to add any code for the route into your startup.cs file; as it’s all contained in the controller file.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram