Endpoint routing in .net core 3.1

The routing process has changed in newer versions of .net core MVC.  You can route either with attribute routing or with conventional routing.  However. it can be confusing if you use both. In this example, I set up examples of both types.

Example: Routing a privacy statement

This example is  to  direct to a privacy statement. Create first a Privacy View in the Home/Views folder. Then add the following to your Home Controller.

public IActionResult Privacy()
{
ViewData["Title"] = "Privacy Statement";
return View();
}

Conventional routing with endpoints

First, I will use conventional routing.  At the top of your startup file, be sure to add the AddControllersWithViews statement.

public void ConfigureServices(IServiceCollection services)
         {
             services.AddControllersWithViews();
....
}

Next, in the configure block, you need both the UseRouting and the UseEndpoints statements.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
...

            app.UseRouting();
           ....
            // optional other statements
            ...
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                     name: "short",
                     pattern: "{action}/{id?}",
                 defaults: new { controller = "Home", action = "Index" });

                endpoints.MapControllerRoute(
                   name: "default",
                   pattern: "{controller}/{action}/{id?}",
               defaults: new { controller = "Home", action = "Index" });
            });
        }

This allows routing by both the URLs example.com/Privacy and example.com/Home/Privacy.

Attribute routing

If I also need the URL, example.com/privacy-statement, then the easiest way is to to use attribute routing. However, the two don’t mix. If you add attribute routes, the conventional routing will be ignored. So, you will have to add all your routes as attributes.

[Route("[action]")]
[Route("privacy-statement")]
public IActionResult Privacy()
 {
 ViewData["Title"] = "Privacy Statement";
 return View();
 }

In this example, both the URLs example.com/privacy and example.com/privacy-statement will work. However, example.com/Home/Privacy will not work because the conventional routing in the startup file will be ignored.

Anchor tag helpers

When you set up, your menus, be sure to use the anchor tag helper attributes asp-controller and asp-action, instead of using an href attribute. For example:

<a asp-controller="Home" asp-action="Privacy">Privacy Statement </a>

This link will then make use of either the endpoint or attribute routing that you have set up. If you change the routing, then the link will automatically also change.

Leave a Reply

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