How do we create a custom route in ASP.NET Core MVC?

In ASP.NET Core MVC, you can create a custom route by using the MapRoute method in the Startup.Configure method. Here is an example:

app.UseEndpoints(endpoints =>
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

        name: "custom",
        pattern: "custom/{controller=Home}/{action=Index}/{id?}",
        defaults: new { controller = "Home", action = "Index" });

In this example, we are defining two routes: the first is the default route and the second is the custom route. The custom route is prefixed with “custom/”, and it will match URLs that start with that prefix.

You can also use MapRoute a method in RouteBuilder a class that can be used to configure custom routes.

    name: "custom",
    template: "custom/{controller=Home}/{action=Index}/{id?}"

You should also note that the custom route should be defined before the default route so that it takes precedence over the default route.

We will be happy to hear your thoughts

Leave a reply