aspnetcore/migration/fx-to-core/areas/http-modules.md
This article shows how to migrate existing ASP.NET HTTP modules from system.webserver to ASP.NET Core middleware.
Before proceeding to ASP.NET Core middleware, let's first recap how HTTP modules work:
Modules are:
Classes that implement xref:System.Web.IHttpModule
Invoked for every request
Able to short-circuit (stop further processing of a request)
Able to add to the HTTP response, or create their own
Configured in Web.config
The order in which modules process incoming requests is determined by:
A series events fired by ASP.NET, such as xref:System.Web.HttpApplication.BeginRequest and xref:System.Web.HttpApplication.AuthenticateRequest. For a complete list, see xref:System.Web.HttpApplication?displayProperty=fullName. Each module can create a handler for one or more events.
For the same event, the order in which they're configured in Web.config.
In addition to modules, you can add handlers for the life cycle events to your Global.asax.cs file. These handlers run after the handlers in the configured modules.
Middleware are simpler than HTTP modules:
Modules, Global.asax.cs, Web.config (except for IIS configuration) and the application life cycle are gone
The roles of modules have been taken over by middleware
Middleware are configured using code rather than in Web.config
:::moniker range=">= aspnetcore-3.0"
:::moniker-end :::moniker range="< aspnetcore-3.0"
:::moniker-end
Middleware are very similar to modules:
Invoked in principle for every request
Able to short-circuit a request, by not passing the request to the next middleware
Able to create their own HTTP response
Middleware and modules are processed in a different order:
Order of middleware is based on the order in which they're inserted into the request pipeline, while order of modules is mainly based on xref:System.Web.HttpApplication?displayProperty=fullName events.
Order of middleware for responses is the reverse from that for requests, while order of modules is the same for requests and responses
Note how in the image above, the authentication middleware short-circuited the request.
An existing HTTP module will look similar to this:
As shown in the Middleware page, an ASP.NET Core middleware is a class that exposes an Invoke method taking an HttpContext and returning a Task. Your new middleware will look like this:
<a name="http-modules-usemiddleware"></a>
The preceding middleware template was taken from the section on writing middleware.
The MyMiddlewareExtensions helper class makes it easier to configure your middleware in your Startup class. The UseMyMiddleware method adds your middleware class to the request pipeline. Services required by the middleware get injected in the middleware's constructor.
<a name="http-modules-shortcircuiting-middleware"></a>
Your module might terminate a request, for example if the user isn't authorized:
A middleware handles this by not calling Invoke on the next middleware in the pipeline. Keep in mind that this doesn't fully terminate the request, because previous middlewares will still be invoked when the response makes its way back through the pipeline.
When you migrate your module's functionality to your new middleware, you may find that your code doesn't compile because the HttpContext class has significantly changed in ASP.NET Core. See Migrate from ASP.NET Framework HttpContext to ASP.NET Core to learn how to migrate to the new ASP.NET Core HttpContext.
HTTP modules are typically added to the request pipeline using Web.config:
Convert this by adding your new middleware to the request pipeline in your Startup class:
The exact spot in the pipeline where you insert your new middleware depends on the event that it handled as a module (BeginRequest, EndRequest, etc.) and its order in your list of modules in Web.config.
As previously stated, there's no application life cycle in ASP.NET Core and the order in which responses are processed by middleware differs from the order used by modules. This could make your ordering decision more challenging.
If ordering becomes a problem, you could split your module into multiple middleware components that can be ordered independently.
Some modules have configuration options that are stored in Web.config. However, in ASP.NET Core a new configuration model is used in place of Web.config.
The new configuration system gives you these options to solve this:
Directly inject the options into the middleware, as shown in the next section.
Use the options pattern:
Create a class to hold your middleware options, for example:
Store the option values
The configuration system allows you to store option values anywhere you want. However, most sites use appsettings.json, so we'll take that approach:
MyMiddlewareOptionsSection here is a section name. It doesn't have to be the same as the name of your options class.
Associate the option values with the options class
The options pattern uses ASP.NET Core's dependency injection framework to associate the options type (such as MyMiddlewareOptions) with a MyMiddlewareOptions object that has the actual options.
Update your Startup class:
Inject the options into your middleware constructor. This is similar to injecting options into a controller.
The UseMiddleware extension method that adds your middleware to the IApplicationBuilder takes care of dependency injection.
This isn't limited to IOptions objects. Any other object that your middleware requires can be injected this way.
The options pattern has the advantage that it creates loose coupling between options values and their consumers. Once you've associated an options class with the actual options values, any other class can get access to the options through the dependency injection framework. There's no need to pass around options values.
This breaks down though if you want to use the same middleware twice, with different options. For example an authorization middleware used in different branches allowing different roles. You can't associate two different options objects with the one options class.
The solution is to get the options objects with the actual options values in your Startup class and pass those directly to each instance of your middleware.
Add a second key to appsettings.json
To add a second set of options to the appsettings.json file, use a new key to uniquely identify it:
Retrieve options values and pass them to middleware. The Use... extension method (which adds your middleware to the pipeline) is a logical place to pass in the option values:
Enable middleware to take an options parameter. Provide an overload of the Use... extension method (that takes the options parameter and passes it to UseMiddleware). When UseMiddleware is called with parameters, it passes the parameters to your middleware constructor when it instantiates the middleware object.
Note how this wraps the options object in an OptionsWrapper object. This implements IOptions, as expected by the middleware constructor.
There are times when converting modules to middleware cannot easily be done. In order to support migration scenarios in which modules are required and cannot be moved to middleware, System.Web adapters support adding them to ASP.NET Core.
In order to support modules, an instance of xref:System.Web.HttpApplication must be available. If no custom xref:System.Web.HttpApplication is used, a default one will be used to add the modules to. Events declared in a custom application (including Application_Start) will be registered and run accordingly.
:::code language="csharp" source="sample8/Program.cs" :::
This infrastructure can be used to migrate usage of Global.asax if needed. The source from Global.asax is a custom xref:System.Web.HttpApplication and the file can be included in an ASP.NET Core application. Since it is named Global, the following code can be used to register it:
:::code language="csharp" source="sample8/Snippets/GlobalSnippet.cs" id="snippet_AddGlobal" :::
As long as the logic within it is available in ASP.NET Core, this approach can be used to incrementally migrate reliance on Global.asax to ASP.NET Core.
In order for the authentication and authorization events to run at the desired time, the following pattern should be used:
:::code language="csharp" source="sample8/Snippets/UseAuthenticationAndAuthorizationSnippet.cs" id="snippet_UseAuthenticationAndAuthorization" :::
If this is not done, the events will still run. However, it will be during the call of .UseSystemWebAdapters().
Because modules and applications in ASP.NET Framework were assigned to a request, a new instance is needed for each request. However, since they can be expensive to create, they are pooled using xref:Microsoft.Extensions.ObjectPool.ObjectPool`1. In order to customize the actual lifetime of the xref:System.Web.HttpApplication instances, a custom pool can be used:
:::code language="csharp" source="sample8/Snippets/HttpModulePoolingSnippet.cs" id="snippet_ObjectPool" :::