Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need to register a route in RouteConfig.cs ASP.Net MVC?

When using a .NET MVC to build a website, when do I need to include a new route's info in RouteConfig.cs?


I have seen there is one default route pre-configured and registered in the RouteConfig.cs file like this:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

When I created a new controller I saw that, without writing any route info in RouteConfig.cs, the corresponding view was rendered in my browser.

Even after creating a few more controllers, like testcontroller, that I accessed from test views, still without writing anything regarding a route for testcontroller, their views rendered properly.

As these views all render without editing anything in RouteConfig.cs, can you give me a few examples when I do need to write route info in RouteConfig.cs?

like image 876
Mou Avatar asked Dec 25 '22 14:12

Mou


1 Answers

The RouteConfig exists for when you want to do a 'non default' route in MVC. As you can see, a lot of your ActionResults will be rendered by matching that route specified there. Ultimately you may be able to create an entire site and not even have to touch the RouteConfig.cs! It's only when you start to want different routes for use cases that you might find yourself diving in there.

An example for when you might need to edit it, is if you had an Area exclusively for blogs and wanted to do something along the lines of:

/Blog/Post/1234/my-blog-post

By default that wouldn't match the default config. In areas the default route config is prefixed by the Area name and then follows the usual standard like so.

/{area}/{controller}/{action}/{id}

In order to get override this we can write the following:

context.MapRoute(
                "Blog",
                "Blog/Post/{id}/{name}",
                new { action = "Index",controller="Post" },
                new { id = @"\d+" }
            );   

It's worth noting that in newer versions of MVC (5 onwards) we have access to the Routing attribute which is an easier and more accessible way to handle routing across controllers and actions.

Article: MVC5.1 Features, Attribute Routing..

Article: MVC5 Attribute Routing via David Hayden


Additional Reading for Routes in ASP.NET MVC ASP.NET MVC Routing Overview

ASP.NET Typical Routing - URL Patterns

like image 63
JonE Avatar answered Apr 19 '23 15:04

JonE