Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (150).NET Core  (24)Angular  (42)ASP.NET  (48)ASP.NET Core  (57)ASP.NET MVC  (84)Azure  (28)Blazor  (74)DocIO  (18)Essential JS 2  (67)Essential Studio  (161)Flutter  (83)JavaScript  (140)Microsoft  (101)PDF  (54)React  (32)Succinctly series  (120)Syncfusion  (459)TypeScript  (30)Uno Platform  (2)UWP  (4)Vue  (26)Webinar  (18)Windows Forms  (54)WPF  (108)Xamarin  (119)XlsIO  (22)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (104)Chart  (44)Cloud  (9)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (3)DataGrid  (36)Development  (245)Doc  (7)DockingManager  (1)eBook  (91)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (16)Extensions  (11)File Manager  (3)Gantt  (8)Gauge  (6)Git  (3)Grid  (25)HTML  (9)Installer  (2)Knockout  (2)LINQPad  (1)Linux  (1)M-Commerce  (1)Metro Studio  (11)Mobile  (186)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (19)Performance  (3)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (5)Road Map  (9)Scheduler  (20)SfDataGrid  (8)Silverlight  (21)Sneak Peek  (14)Solution Services  (2)Spreadsheet  (4)SQL  (5)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (9)Tips and Tricks  (42)UI  (104)Uncategorized  (68)Unix  (2)User interface  (67)Visual State Manager  (1)Visual Studio  (17)Visual Studio Code  (9)Web  (161)What's new  (108)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
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 forumDirect-Trac, or feedback portal. We are always happy to assist you!

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

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top