Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline. Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.
Request delegates are configured using [Run](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.runextensions), [Map](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.mapextensions), and [Use](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.useextensions) extension methods on the [IApplicationBuilder](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.iapplicationbuilder) instance that is passed into the `Configure` method in the `Startup` class. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are *middleware*, or *middleware components*. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline, or short-circuiting the chain if appropriate.
[Migrating HTTP Modules to Middleware](../migration/http-modules.md) explains the difference between request pipelines in ASP.NET Core and the previous versions and provides more middleware samples.
## Creating a middleware pipeline with IApplicationBuilder
The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the next, as this diagram shows (the thread of execution follows the black arrows):
![Request processing pattern showing a request arriving, processing through three middlewares, and the response leaving the application. Each middleware runs its logic and hands off the request to the next middleware at the next() statement. After the third middleware processes the request, it's handed back through the prior two middlewares for additional processing after the next() statements each in turn before leaving the application as a response to the client.](middleware/_static/request-delegate-pipeline.png)
Each delegate has the opportunity to perform operations before and after the next delegate. A delegate can decide to not pass a request to the next delegate -- this is referred to as short-circuiting the request pipeline. Short-circuiting is often desirable because it allows unnecessary work to be avoided. For example, the static file middleware can return a request for a static file and short circuit the rest of the pipeline. Exception handling delegates need to be called early on in the pipeline, so they are able to catch exceptions that occur in later stages of the pipeline.
The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. In this case, there isn't really a request "pipeline", rather a single anonymous function that is called in response to every HTTP request.
You chain multiple request delegates together with [app.Use](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.useextensions). The `next` parameter represents the next delegate in the pipeline. You can terminate (short-circuit) the pipeline by *not* calling the *next* parameter. You can typically perform actions both before and after the next delegate, as this example demonstrates:
>Be careful modifying the `HttpResponse` after invoking `next`, as the response may have already been sent to the client. [HttpResponse.HasStarted](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.http.features.httpresponsefeature#Microsoft_AspNetCore_Http_Features_HttpResponseFeature_HasStarted) can be used to check if the headers have been sent yet.
The order middleware components are added in the `Configure` method is the order in which they are invoked on requests, and the reverse order for the response. This ordering is critical for security, performance, and functionality.
In the code above, `UseExceptionHandler` is the first middleware added to the pipeline -- therefore it will catch any exceptions that occur in later calls.
The static file middleware is called early in the pipeline so it can handle requests and short circuit without going through the remaining components. The static file middleware provides **no** authorization checks. Any files served by it, including those under *wwwroot* are publicly available. See [Working with static files](xref:fundamentals/static-files) for an approach to secure static files.
If the request is not handled by the static file middleware, it's passed on to the Identity middleware (`app.UseIdentity`), which performs authentication. Identity does not short circuit unauthenticated requests. Identity authenticates requests, but authorization (and rejection) does not happen until after MVC selects a specific controller and action.
The following example demonstrates a middleware ordering where requests for static files are handled by the static file middleware before the response compression middleware. Static files are not compressed with this ordering of the middleware. The MVC responses from [UseMvcWithDefaultRoute](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.mvcapplicationbuilderextensions#Microsoft_AspNetCore_Builder_MvcApplicationBuilderExtensions_UseMvcWithDefaultRoute_Microsoft_AspNetCore_Builder_IApplicationBuilder_) can be compressed.
You configure the HTTP pipeline using `Run`, `Map`, and `Use`. The `Run` method short circuits the pipeline (that is, it will not call a `next` request delegate). `Run` is a convention, and some middleware components may expose `Run[Middleware]` methods that run at the end of the pipeline.
`Map*` extensions are used as a convention for branching the pipeline. [Map](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.mapextensions) branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.
[MapWhen](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.mapwhenextensions) branches the request pipeline based on the result of the given predicate. Any predicate of type `Func<HttpContext, bool>` can be used to map requests to a new branch of the pipeline. In the following example, a predicate is used to detect the presence of a query string variable `branch`:
Middleware is generally encapsulated in a class and exposed with an extension method. Consider the following middleware, which sets the culture for the current request from the query string:
The following extension method exposes the middleware through [IApplicationBuilder](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.iapplicationbuilder):
Middleware should follow the [Explicit Dependencies Principle](http://deviq.com/explicit-dependencies-principle/) by exposing its dependencies in its constructor. Middleware is constructed once per *application lifetime*. See *Per-request dependencies* below if you need to share services with middleware within a request.
Middleware can resolve their dependencies from dependency injection through constructor parameters. [`UseMiddleware<T>`](https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.builder.usemiddlewareextensions#methods_summary) can also accept additional parameters directly.
Because middleware are constructed at app startup, not per-request, *scoped* lifetime services used by middleware constructors will not be shared with other dependency-injected types during each request. If you need to share a *scoped* service between your middleware and other types, you should add these services to the `Invoke` method's signature. The `Invoke` method can accept additional parameters that will be populated by dependency injection. For example:
```c#
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext, IMyScopedService svc)