Where is the best place to generate routes in an MVC-application?

Asked
Active3 hr before
Viewed126 times

7 Answers

applicationplacegenerate
90%

Thus, routing plays important role in MVC framework. , Entity Framework , Routing ,Routing plays important role in the MVC framework. Routing maps URL to physical file or class (controller class in MVC).

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

      routes.MapRoute(
         name: "Student",
         url: "students/{id}",
         defaults: new {
            controller = "Student", action = "Index"
         }
      );

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

Meta Stack Overflow , Stack Overflow help chat , Stack Overflow Public questions & answers , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers

Should the links be generated in the view that calls the template, together with the Commentable model? i.e.

< ? php
echo $this - > partial('path/to/template/comments.phtml', array(
         'add-link' => $this - > url($params, $routeName),
         'load-link' => $this - > url($params, $routeName),
         'comments' => $this - > model - > getComments()
      );
load more v
72%

When you create a new ASP.NET MVC application, the application is already configured to use ASP.NET Routing. ASP.NET Routing is setup in two places.,The file in Listing 1 contains the default Global.asax file for an ASP.NET MVC application.,When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.,Second, and more importantly, a route table is created in the application's Global.asax file. The Global.asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event.

Listing 1 - Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1 {
   // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
   // visit https://go.microsoft.com/?LinkId=9394801

   public class MvcApplication: System.Web.HttpApplication {
      public static void RegisterRoutes(RouteCollection routes) {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new {
               controller = "Home", action = "Index", id = ""
            } // Parameter defaults
         );
      }

      protected void Application_Start() {
         RegisterRoutes(RouteTable.Routes);
      }
   }
}
load more v
65%

As an extra benefit to this design, you can now change your controller and action method names without breaking any bookmarks scattered around the Web because they're no longer part of your site's URLs. , Avoid optional and default values for items in your URL. Optional and default values for URL items create routes that apply to URLs of varying lengths, making it harder to determine what route leads to what action method., This route clearly links the URL http://MyServer.com/Customer/Sales/A123/2016 to the CustomerMaster controller's GetSales method while setting the CustId and Year parameter to A123 and 2016, respectively. No doubt, no question. , However, following my rules will cause you to have one route for every controller/action method in your application. I can see that could be overwhelming, especially in a large application. In that case, you have my permission to embed your action method names in your routes. I know that's all that was standing in your way.

A typical route that follows these rules looks like this:

routes.MapRoute(_ "GetCustomerSales", _ "Customer/Sales/{CustId}/{Year}", _ New With {
         .controller = "CustomerMaster", .action = "GetSales"
      }
75%

Note: Always put the more specific route on the top order while defining multiple routes, since the routing system checks the incoming URL pattern from the top and as it gets the matched route it will consider that. It will not check further routes after the matching pattern.,The point that you need to remember is, the Route Names must be unique. You can register multiple custom routes with different names. Consider the following example where we register the “Employee” route.,As we already discussed, if we want to configure any routes then we need to configure the routes within the RegisterRoute method of RouteConfig class using the MapRoute extension method. While configuring the Routes, at least two parameters we need to provide to the MapRoute method i.e. Route name and URL pattern. The Default parameter is optional. ,The ASP.NET MVC framework evaluates each route in sequence. It starts with the first configured route and if the incoming URL doesn’t satisfy the First URL pattern of the route then it will evaluate the second route and so on. In the above example, the routing engine will evaluate the Employee route first and if the incoming URL doesn’t start with domainName/Employee then only it will consider the second route which is the default route.

The point that you need to remember is, the Route Names must be unique. You can register multiple custom routes with different names. Consider the following example where we register the “Employee” route.

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

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

         routes.MapRoute(
            name: "Default", //Route Name
            url: "{controller}/{action}/{id}", //Route Pattern
            defaults: new {
               controller = "Home", //Controller Name
                  action = "Index", //Action method Name
                  id = UrlParameter.Optional //Defaut value for above defined parameter
            }
         );
      }
   }
}
load more v
40%

The default routes that Visual Studio creates for a new project assumes that you will follow this convention. But if you want to follow your own convention then you would need to modify the routes.,When Visual Studio creates the MVC project, it adds some default routes to get us started. When you run your application, you will see that Visual Studio has directed the browser to port 63664. You will almost certainly see a different port number in the URL that your browser requests because Visual Studio allocates a random port when the project is created.,This is the code from the application start event in Global.asax from the MVC App which we created in the previous chapter.,If you append /Home or /Home/Index to the URL and press ‘Enter’ button, you will see the same result from the MVC application.

This is the code from the application start event in Global.asax from the MVC App which we created in the previous chapter.

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVCFirstApp {
   public class MvcApplication: System.Web.HttpApplication {
      protected void Application_Start() {
         AreaRegistration.RegisterAllAreas();
         RouteConfig.RegisterRoutes(RouteTable.Routes);
      }
   }
}
load more v
22%

It is always good to specify a route name while creating the routes. It gives the route a logical name so that we can use the named route for URL generation.,When we create a new ASP.NET Core MVC application using the default template, the application configures a default routing. Let’s create a new project and examine this.,Testing ASP.NET Core Applications,Creating a Conventional Routing pattern for an ASP.NET Core MVC application

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

Other "application-place" queries related to "Where is the best place to generate routes in an MVC-application?"