DEV Community

loading...
Cover image for How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware
Syncfusion, Inc.

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

sureshmohan profile image Suresh Mohan Originally published at syncfusion.com on ・5 min read

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.
        } 
    }
Enter fullscreen mode Exit fullscreen mode

Code used in web.config

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

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>"); 
            };
        }   
    }
Enter fullscreen mode Exit fullscreen mode

Code used in web.config

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

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.

Run To terminate the HTTP pipeline.
Use To add the middleware to the request pipeline.
Map To match the request delegate based on the request path.
MapWhen Supports 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.
       }
  }
Enter fullscreen mode Exit fullscreen mode
  1. Create an extension method on the ApplicationBuilder file to use the RedirectionHandlerMiddleware in the request pipeline.
  2. 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>();
     }
}
Enter fullscreen mode Exit fullscreen mode
  1. 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();
         });

Enter fullscreen mode Exit fullscreen mode

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>");
       }
 }
Enter fullscreen mode Exit fullscreen mode
  1. Like in the migration from HTTP handler to middleware, we need to add an extension method to add the middleware in the request pipeline.
  2. 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>();
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. 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();
         });

Enter fullscreen mode Exit fullscreen mode

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 forum, Direct-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:

Discussion (0)

pic
Editor guide