ASP.NET MVC > Route

Custom route handler to redirect user to specific page in ASP.NET MVC

How to create a custom route handler in ASP.NET MVC to redirect the user to a specific page for a specific url?


Custom route handler is used in a very specific scenario where we need to redirect the user to any external page or shortened the long url or making the url more user friendly, readable and memorable.

To create a custom route handler, first create a .cs file and implement IRouteHandler interface. IRouteHandler interface contains GetHttpHandler method that returns IHttpHandler. In our case, we have created MyCustomRouteHandler class inside Utility folder.

UTILITY/MYCUSTOMROUTEHANDLER.CS CODE

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

namespace MVCTraining5.Utility
{
    public class MyCustomRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new MyClassHttpHandler();
        }
    }
    
    public class MyClassHttpHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        } 

        public void ProcessRequest(HttpContext context)
        { 
            context.Response.Redirect("http://www.itfunda.com", true);
        }
     }
}

In the above code, we have first created a class MyCustomRouteHandler that inherits IRouteHandler interface. This interface has a method called GetHttpHandler that returns IHttpHandler interface. In our case, we have returned MyClassHttpHandler class (defined in the same .cs file that implements IHttpHandler interface).

MyClassHttpHandler class implements two methods IsReusable and ProcessRequest of IHttpHandler. IsReusable simply instruct the MVC framework whether this instance of IHttpHandler is reusable. The ProcessRequest method in this case simply redirects the user to http://www.itfunda.com website.

After defining the MyCustomRouteHandler, we need to add it to the RouteCollection (register it).

APP_START/ROUTECONFIG.CS CODE

public static void RegisterRoutes(RouteCollection routes)
        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            
            routes.Add(new Route("itfunda", new
MVCTraining5.Utility.MyCustomRouteHandler()));
            
// default route routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }

Here, we have added MyCustomRouteHandler into the Routes collection. Notice the first parameter of the Route constructor while adding to the Routes collection, it is “itfunda” (that is the url for which this custom route to call). Now run the project.

When browser request the url http://localhost:63087/itfunda, the user gets redirected to “http://www.itfunda.com” website.

 Views: 3168 | Post Order: 72



Write for us