ASP .NET MVC has provide more flexible options to extend the functionality to make a programmer easy and smooth.  Custom route handlers are one of them.

How MVC Routing Works?

URLs are very important part of our web based application. Routing will decide which handler will be responsible to handle the incoming request from the browser and responsible  for match the incoming URL with route table to proceed. Let we understand more on routing  here.

Why and Where We Need a Custom Route Handler?

Scenario 1: If we decide to process some data before creating the instance of the controller.

Scenario 2: It will helpful when we need to redirect the user to any external page or shortened the long URLs or making the URLs more user-friendly.

What is Route Handlers ?

From MSDN – ” MvcRouteHandler. This class implements IRouteHandler, therefore it can integrate with ASP.NET routing. The MvcRouteHandler class associates the route with an MvcHandler instance. A MvcRouteHandler instance is registered with routing when you use the MapRoutemethod. When the MvcRouteHandler class is invoked, the class generates an MvcHandler instance using the current RequestContextinstance. It then delegates control to the new MvcHandler instance.”

In simple, it is a class that implements IRouteHandler interface, which provides route handler class instance to process the request. IRouteHandler has only one method that is GetHttpHandler().

Create Custom Route -dotnet-helpers3

Creating A Custom Route Handler

Create CustomeRouteHandler.cs file in Utility folder (It created for placing common functionality) and implement IRouteHandler interface as shown below. IRouteHandler interface contains GetHttpHandler method that returns IHttpHandler

From the above code, we have returned CustomHttpHandler class. CustomHttpHandleris class which 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 https://www.dotnet-helpers.com website. 

After defining the MyCustomRouteHandler, we need to add it to the RouteCollection under App_Start -> RouteConfig.cs

Run the application , when we hit the URL  http://localhost:8080/NonAdminUser then it will redirect to the https://www.dotnet-helpers.com.

Keep cool coding…