Click here to Skip to main content
15,883,901 members
Articles / Programming Languages / C#
Tip/Trick

Understanding Routes Registration in nopCommerce ASP.NET (MVC)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
14 Nov 2015CPOL4 min read 25.2K   10   1
In this tip, we will look into new route registration process (ASP.NET Routing) in nopCommerce.

Introduction

In this tip, we will look into new route registration process (ASP.NET Routing) in nopCommerce.

Background

Registering New Routes (ASP.NET Routing)

With the help of ASP.NET routing, you can map URLs that do not have to map directly to web files in your website. Basically, the ASP.NET routing module is responsible for mapping all the incoming browser requests to particular MVC controller actions.

For more detailed information, check the following:

The ASP.NET MVC framework and ASP.NET Dynamic Data extend routing to provide features that are used only in MVC applications and in Dynamic Data applications. For more information about MVC, see ASP.NET MVC 3. For more information about Dynamic Data, see ASP.NET Dynamic Data Content Map.

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.

Using the Code

nopCommerce is based on ASP.NET (MVC) and it follows the IRouteProvider interface for registering the routes during the application start event. All the routes are registered in the "Route Provider" class in the Nop.Web project.

nopCommerce is open-source, the source code is available free for download: CLICK HERE

In order to view the "Route Provider" class, go to: Nop.Web/Infrastructure/RouteProvider.cs.

You will see the route registration of the homepage:

C#
using System.Web.Mvc;
using System.Web.Routing;
using Nop.Web.Framework.Localization;
using Nop.Web.Framework.Mvc.Routes;

namespace Nop.Web.Infrastructure
{
    public partial class RouteProvider : IRouteProvider
    {
        public void RegisterRoutes(RouteCollection routes)
        {
            //We reordered our routes so the most used ones are on top. It can improve performance.

            //home page
            routes.MapLocalizedRoute("HomePage",
                            "",
                            new { controller = "Home", action = "Index" },
                            new[] { "Nop.Web.Controllers" });

You can use this "Route Provider" class for the following:

  • Plugins custom routes
  • New custom pages

For example: In plugins, you need to create a new class while implementing the IRouteProvider interface. After that, simply register the routes that are specific to your new plugin.

Some other examples of how route is registered in nopCommerce are as follows:

C#
//widgets
            //we have this route for performance optimization 
            //because named routes are MUCH faster than usual Html.Action(...)
            //and this route is highly used
            routes.MapRoute("WidgetsByZone",
                            "widgetsbyzone/",
                            new { controller = "Widget", action = "WidgetsByZone" },
                            new[] { "Nop.Web.Controllers" });

            //login
            routes.MapLocalizedRoute("Login",
                            "login/",
                            new { controller = "Customer", action = "Login" },
                            new[] { "Nop.Web.Controllers" });
            //register
            routes.MapLocalizedRoute("Register",
                            "register/",
                            new { controller = "Customer", action = "Register" },
                            new[] { "Nop.Web.Controllers" });
            //logout
            routes.MapLocalizedRoute("Logout",
                            "logout/",
                            new { controller = "Customer", action = "Logout" },
                            new[] { "Nop.Web.Controllers" });

            //shopping cart
            routes.MapLocalizedRoute("ShoppingCart",
                            "cart/",
                            new { controller = "ShoppingCart", action = "Cart" },
                            new[] { "Nop.Web.Controllers" });
            //wishlist
            routes.MapLocalizedRoute("Wishlist",
                            "wishlist/{customerGuid}",
                            new { controller = "ShoppingCart", 
                            action = "Wishlist", customerGuid = UrlParameter.Optional },
                            new[] { "Nop.Web.Controllers" });

Explanation

C#
//login
            routes.MapLocalizedRoute("Login",	// ROUTE NAME
                            "login/",			// URL
                            new { controller = "Customer", action = "Login" },  // PARAMETERS DEFAULTS
                            new[] { "Nop.Web.Controllers" });

You must be wondering how exactly routing works in nopCommerce (or even ASP.NET MVC)? Basically, routing in your application determines what controller needs to be triggered that will handle the request. Along the request, appropriate action is also invoked depending on the parameters that are being sent. MVCRouteHandler digests all this information in order to make a decision.

In addition to this, an another appropriate question should be - why you need routing in your website? Why nopCommerce is using this routing for URLs? The answer is quite simple, these days everybody wants their website to offer SEO friendly URLs. With the help of this routing technique in ASP.NET MVC, nopCommerce uses IRouteProvider interface for route registration during application startup. All the core routes are then registered in the RouteProvider class located in the Nop.Web project.

Localizable URL

In nopCommerce, if you look into the Nop.Web project (RouteProvider.cs), you will find that some of the routes are declared with routes.MapRoute() while some routes are declared with routes.MapLocalizedRoute(). The main difference between the two is to basically support multi-language and to have SEO friendly URLs.

Here is an example of routes.MapRoute() in nopCommerce (RouteProvider.cs):

C#
routes.MapRoute("WidgetsByZone",
                            "widgetsbyzone/",
                            new { controller = "Widget", action = "WidgetsByZone" },
                            new[] { "Nop.Web.Controllers" });

//install
            routes.MapRoute("Installation",
                            "install",
                            new { controller = "Install", action = "Index" },
                            new[] { "Nop.Web.Controllers" });

Here is an example of routes.MapLocalizedRoute() in nopCommerce (RouteProvider.cs):

C#
//register
            routes.MapLocalizedRoute("Register",
                            "register/",
                            new { controller = "Customer", action = "Register" },
                            new[] { "Nop.Web.Controllers" });

//shopping cart
            routes.MapLocalizedRoute("ShoppingCart",
                            "cart/",
                            new { controller = "ShoppingCart", action = "Cart" },
                            new[] { "Nop.Web.Controllers" });

nopCommerce is a great e-Commerce solution that supports multi-language and if your online store is based on nopCommerce and making the use of multi-language feature, the chances are that the audience / visitors will be from different parts of the world who speak different languages. Many online shoppers prefer visiting a website that offers content in their own language.

With the help of routing, nopCommerce assigns a specified culture (specific language code / localization) into the URL. In ASP.NET MVC, you can create a route that has the culture build into it like this:

C#
routes.MapRoute(
      "Default",          // This will be the route name
      "{culture}/{controller}/{action}/{id}",     // This will be the URL along with parameters
      new { culture="en-US", controller = "Home",
      action = "Index", id = "" }  // Parameter defaults goes here
  );

Here is an example of how nopCommerce adds language ID in the URL:

C#
//change language (AJAX link)
           routes.MapLocalizedRoute("ChangeLanguage",
                           "changelanguage/{langid}",
                           new { controller = "Common", action = "SetLanguage" },
                           new { langid = @"\d+" },
                           new[] { "Nop.Web.Controllers" });

Example of nopCommerce blog feed route with language ID in the URL:

C#
//blog RSS
           routes.MapLocalizedRoute("BlogRSS",
                           "blog/rss/{languageId}",
                           new { controller = "Blog", action = "ListRss" },
                           new { languageId = @"\d+" },
                           new[] { "Nop.Web.Controllers" });

Let's say we have one language stored in the nopCommerce, we can see that in: Administration > Configuration > Languages

Now, if we look into the nopCommerce database, we can see that one language is stored in the database (English) with the language culture specified as en-US - Language ID is 1.

Let us view the nopCommerce news feed in browser with language ID specified in the URL:

Now, if we try to relate the above screenshot with what we have in our nopCommerce (RouteProvider.cs), we can easily see how route is being registered in the code:

C#
//news RSS
            routes.MapLocalizedRoute("NewsRSS",
                            "news/rss/{languageId}",
                            new { controller = "News", action = "ListRss" },
                            new { languageId = @"\d+" },
                            new[] { "Nop.Web.Controllers" });

More examples of product routes in nopCommerce:

C#
//product search
           routes.MapLocalizedRoute("ProductSearch",
                           "search/",
                           new { controller = "Catalog", action = "Search" },
                           new[] { "Nop.Web.Controllers" });

//recently viewed products
           routes.MapLocalizedRoute("RecentlyViewedProducts",
                           "recentlyviewedproducts/",
                           new { controller = "Product",
                           action = "RecentlyViewedProducts" },
                           new[] { "Nop.Web.Controllers" });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
Founder of Striving Programmers Online Community: http://www.strivingprogrammers.com

I am a programmer / web developer / software developer / graphic designer / database administrator.

Working with .NET Frameworks 2.0/3.5/4.0, MS SQL Server 2000/2005/2008, Oracle 8i/9i/10G, ASP.NET, C#.NET, VB.NET, ASP.NET AJAX, ASP.NET MVC, Web Services, JQuery, HTML, CSS, JavaScript and other programming languages .

Proficient in designing tools: Adobe Photoshop & Adobe Illustrator

Comments and Discussions

 
QuestionMapLocalizedRoute is not a member of Routecollection Pin
KaranTrivedi25-May-17 2:36
KaranTrivedi25-May-17 2:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.