Click here to Skip to main content
14,139,809 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

15.8K views
14 bookmarked
Posted 21 Sep 2014
Licenced CPOL

Routing in MVC

, 21 Sep 2014
Rate this:
Please Sign up or sign in to vote.
Routing in MVC

Introduction

Before we get into how URL Routing works in MVC, let's have a quick look at the MVC architecture.

By seeing this high level architecture diagram, we can say that the Controller will handle the user requests. The complete flow is as follows:

  • User’s request is first passed to the controller
  • Controller parses the request and gets the required data from Model
  • After getting required data, it is passed to view
  • And finally, controller sends it to User browser as a Response

Now where comes the routing in the above model that should be the next question and the answer is the below image which shows routing is the first important thing in MVC.

Step by Step Routing Implementation

In ASP.NET traditional web forms, what happens is user is directly redirected to the resources requested but in MVC, it matches the incoming requests that would otherwise match a resource on file system and maps the request to a controller action. Basically, I would say it constructs the outgoing URLs that correspond to controller actions.

Some of the developers compare ASP.NET routing with URL rewriting and the key difference between the two is Routing generates URLs using the same mapping that it used to match incoming URLs. On the other hand, URL rewriting applies to incoming requests and does not help in generating same URLs.

How to Define a Route

Defining Route starts with a URL Pattern which specifies the pattern which the route will match. Along with the route, URL route can also specify default values and constraints for the various parts of the URL providing tight control over how and when the route matches incoming request URLs.

One Routing URL pattern can serve for a group of similar URLs request by a user and the pattern helps the routing engine to correctly serve the URL with correct controller and actions.

In ASP.NET MVC, Routing is supported by default. We can register route patterns in RegisterRoutes (RouteCollection routes) method from the Application_Start eventhandler of Global.asax file. Where in, RouteCollection is a collection of routes registered with the application.

The default route pattern is given as {controller}/{action}/{id}. Below is the sample of code where the routes are registered.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCWithEF
{
    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 },
                namespaces: new string[] { "MVCWithEF.Controllers" }
            );
        }
    }
}

As we can observe in RegisterRoutes method, there is a Default Route pattern registered and even we can add our custom route patterns into RouteCollection.

In the above code, the first line under RegisterRoutes method tells that request having .asxd extention will not be handled by routing of ASP.NET routing as this has to be handled by HTTPHandler. We can also ensure that routing ignores such request. We can use StopRoutingHandler and the above modified code would be as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCWithEF
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.Add(new Route
                (
                    "{resource}.axd/{*pathInfo}",
                    new StopRoutingHandler()
                ));             
                routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", 
                action = "Index", id = UrlParameter.Optional },
                namespaces: new string[] { "MVCWithEF.Controllers" }
            );
        }
    }
}

and the defaults for this pattern are given as:

  • controller - Home
  • action - Index
  • Id - it's an optional parameter as defined by UrlParameter.Optional

Now suppose we have a Controller called Home and inside controller, there is an action called Index as defined below, then request will be sent to /Home/Index.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCWithEF.Common;
using System.Data.Entity;
using System.Web.Caching;

namespace MVCWithEF.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult  Index()
        {
            return View();
        }
    }
}

Points of Interest

There are some points which need to be discussed such as:

  • StopRouteHandler
  • Constraints
  • Custom Router

But to learn the basics of router, the above information would be useful.

License

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

Share

About the Author

Arora Sumit
Technical Lead
India India
Working as .Net Technical Lead in a reputed MNC and having more than 8 years of experience in developing .Net Applications

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Bharatrk23-Sep-14 0:16
memberBharatrk23-Sep-14 0:16 
GeneralMy vote of 5 Pin
SinghSaurabh198921-Sep-14 21:20
memberSinghSaurabh198921-Sep-14 21:20 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun21-Sep-14 18:00
memberHumayun Kabir Mamun21-Sep-14 18:00 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190518.1 | Last Updated 21 Sep 2014
Article Copyright 2014 by Arora Sumit
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid