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…