How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (219)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (917)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (149)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (631)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (595)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware

How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware

ASP.NET Core is a cross-platform, open-source framework for developing web applications in Windows, Mac, and Linux operating systems (OS). You can develop an ASP.NET Core web application using any of the following IDEs:

In this blog post, we will learn how to migrate ASP.NET HTTP handlers and modules to ASP.NET Core middleware with appropriate code examples.

Let’s get started!

ASP.NET HTTP handlers

In an ASP.NET web application, the HTTP handler is a process that is executed on each response to the requests made to the web server. We can create our own custom HTTP handlers to render desired output.

Handler class for redirection

The following is the code to redirect all the .aspx extension pages to a new page.

public class RedirectionHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        } 
		
        public void ProcessRequest(HttpContext context)
        {
            var response = context.Response; 
            response.Write("<p>Process files with .aspx extension</p>");
           
			// Any redirection logic can be written here.
        } 
    }

Code used in web.config

<!--Code inside configuration -> system.webServer -> handlers section -->
<add name="RedirectionHandler" verb="*" path="*.aspx" type="MyWebApplication.RedirectionHandler" resourceType="Unspecified"/>

ASP.NET HTTP modules

The HTTP modules will also be executed for each request to the application before and after the HTTP handler’s execution. They help us to verify the incoming and outgoing requests and modify them.

Module class for restricting users

The following is the HTTP module code used to restrict a user based on their IP (internet protocol) address.

public class IPRestrictionModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += (source, arguments) =>
            {
                var application = (HttpApplication)source;
                var beginContext = application.Context; 
                beginContext.Response.Write("<p>Restrict Users based on IP</p>");
				
				// Code logic comes here.
            }; 
           
          context.EndRequest += (source, arguments) =>
            {
                var application = (HttpApplication)source;
                var endContext = application.Context; 
                endContext.Response.Write("<p>Request ended.</p>"); 
            };
        } 	
	}

Code used in web.config

<!-- Code inside configuration -> system.webServer -> modules section -->
<add name="RestrictionModule" type=" MyWebApplication.IPRestrictionModule" />

ASP.NET Core middleware

In an ASP.NET Core application, the middleware component will replace both the HTTP handler and modules. It is a component that is executed on every request. We can add the middleware in the Configure method of the Startup class using the IApplicationBuilder interface.

We can use the following four methods of the Application Builder file that are passed to the Request Delegate.

RunTo terminate the HTTP pipeline.
UseTo add the middleware to the request pipeline.
MapTo match the request delegate based on the request path.
MapWhenSupports predicate-based middleware branching, allowing separate pipelines.

Let’s see how to migrate ASP.NET HTTP handlers to ASP.NET Core middleware!

Migrating HTTP handlers to middleware

The HTTP handler can be migrated to the middleware as follows.

  1. Add a class named RedirectionHandlerMiddleware and use the following code in it.
    public class RedirectionHandlerMiddleware
     {
         private RequestDelegate _next;
    
          public RedirectionHandlerMiddleware (RequestDelegate next)
          {
               _next = next;
          }
    
           public async Task Invoke(HttpContext context)
           {
               await context.Response.WriteAsync("<p>Process files with .aspx extension</p>");
    
               // Any Redirection logic can be return here.
           }
      }
  2. Create an extension method on the ApplicationBuilder file to use the RedirectionHandlerMiddleware in the request pipeline.
  3. Then, create a class named MiddlewareExtension for the created extension and use the following code in it.
    public static class MiddlewareExtension    	
    {
         public static IApplicationBuilder UseRedirectionHanlderMiddleware
                       (this IApplicationBuilder applicationBuilder)
         {
             return applicationBuilder.UseMiddleware<RedirectionHandlerMiddleware>();
         }
    }
  4. Then, we need to include the next code in the startup.cs file.
    app.MapWhen(context => context.Request.Path.ToString().EndsWith(".aspx"),
         	appBuilder => {
             	appBuilder.UseRedirectionHanlderMiddleware();
        	 });
    

Now, we have finished migrating the ASP.NET HTTP handlers to ASP.NET Core middleware. Let’s talk about the modules to middleware migration.

Migrating HTTP modules to middleware

The previously mentioned HTTP module can be migrated to middleware as follows.

  1. Add a class named IPRestrictionModuleMiddleware with the following code.
    public class IPRestrictionModuleMiddleware 
      {
           private RequestDelegate _next;
           public IPRestrictionModuleMiddleware (RequestDelegate next)
           {
               _next = next;
           }
           public async Task Invoke(HttpContext context)
           {
                await context.Response.WriteAsync("<p>Begin request</p>");
                await _next.Invoke(context);
                await context.Response.WriteAsync("<p>End request</p>");
           }
     }
  2. Like in the migration from HTTP handler to middleware, we need to add an extension method to add the middleware in the request pipeline.
  3. Then, add the following code in the existing extension class MiddlewareExtension.
    public static class MiddlewareExtensions    	
    {
        public static IApplicationBuilder UseRedirectionHanlderMiddleware
               (this IApplicationBuilder applicationBuilder)
        {
            return applicationBuilder.UseMiddleware<RedirectionHandlerMiddleware>();
        }
    		
        public static IApplicationBuilder UseIPRestrictionModuleMiddleware
               (this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<IPRestrictionModuleMiddleware>();
        }
    }
  4. Then, include the middleware in the startup.cs file.
    // For Module
     app.UseIPRestrictionModuleMiddleware();
    
     // For Handler
    app.MapWhen(context => context.Request.Path.ToString().EndsWith(".aspx"),
         	appBuilder => {
             		appBuilder.UseRedirectionHanlderMiddleware();
        	 });
    

Thus, we have finished migrating ASP.NET HTTP modules to ASP.NET Core middleware!

Conclusion

Thanks for reading! In this blog post, we have seen how to easily migrate ASP.NET HTTP handlers and modules to ASP.NET Core middleware. Try out the steps given in this blog and leave your feedback in the comments section below!

With over 70 components, the ASP.NET Core toolkit powered by Essential JS 2 contains all you need for building line-of-business applications. It includes popular widgets such as a data grid, chart, Gantt chart, diagram, spreadsheet, scheduler, and pivot grid. Use them to enhance your productivity!

If you have questions, you can contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

If you like this blog post, we think you will also like the following articles:

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed