How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware
Tags: webdev, csharp, dotnet
Published: 2021-02-26 04:54:17

---
title: How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware
published: true
date: 2021-02-23 11:00:13 UTC
tags: webdev, csharp, dotnet
canonical_url: https://www.syncfusion.com/blogs/post/how-to-migrate-asp-net-http-handlers-and-modules-to-asp-net-core-middleware.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2021/02/How-to-Migrate-ASP.NET-HTTP-Handlers-and-Modules-to-ASP.NET-Core-Middleware-672x372.png
---

[ASP.NET Core](https://dotnet.microsoft.com/learn/aspnet/what-is-aspnet-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:

- [Visual Studio](https://visualstudio.microsoft.com/)
- [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/)
- [Visual Studio Code](https://code.visualstudio.com/)

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](https://en.wikipedia.org/wiki/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](https://docs.microsoft.com/en-us/previous-versions/aspnet/bb398986(v=vs.100)#creating-a-custom-http-handler) to render desired output.

**Handler class for redirection**

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

```csharp
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**

```html
<!--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](https://docs.microsoft.com/en-us/previous-versions/aspnet/bb398986(v=vs.100)#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.

```csharp
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**

```html
<!-- 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](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0) 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.**

<table>
<tbody>
<tr style="background: none;">
<td width="131">Run</td>
<td width="492">To terminate the HTTP pipeline.</td>
</tr>
<tr>
<td width="131">Use</td>
<td width="492">To add the middleware to the request pipeline.</td>
</tr>
<tr>
<td width="131">Map</td>
<td width="492">To match the request delegate based on the request path.</td>
</tr>
<tr>
<td width="131">MapWhen</td>
<td width="492">Supports predicate-based middleware branching, allowing separate pipelines.</td>
</tr>
</tbody>
</table>

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

## Migrating HTTP handlers to middleware

The [HTTP handler](#asp-net-http-handlers) can be migrated to the middleware as follows.

1. Add a class named **RedirectionHandlerMiddleware** and use the following code in it.
```csharp
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.
```csharp
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](#asp-net-http-modules) can be migrated to middleware as follows.

1. Add a class named **IPRestrictionModuleMiddleware** with the following code.
```csharp
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.**
```csharp
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.
```csharp
// 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](https://www.syncfusion.com/aspnet-core-ui-controls) toolkit powered by [Essential JS 2](https://www.syncfusion.com/javascript-ui-controls) 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](https://www.syncfusion.com/forums), [Direct-Trac](https://www.syncfusion.com/support/directtrac/incidents), or [feedback portal](https://www.syncfusion.com/feedback). We are always happy to assist you!

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

- [How to Migrate SQL Server in an ASP.NET MVC Application to MySQL and PostgreSQL](https://www.syncfusion.com/blogs/post/how-to-migrate-sql-server-in-an-asp-net-mvc-application-to-mysql-and-postgresql.aspx) [Blog]
- [Migrate Windows Desktop Applications to the Web with Syncfusion + Wisej](https://dev.to/syncfusion/migrate-windows-desktop-applications-to-the-web-with-syncfusion-wisej-4o16) [Blog]
- _[HTTP Succinctly](https://www.syncfusion.com/ebooks/http)_ [E-book]