ASP.NET Core Startup Class Configure() Method | Detailed Explanation of ASP.NET Core Middleware

2019年12月15日 2860点热度 0人点赞 2条评论
内容目录

The startup process of ASP.NET Core applications is as follows

Table of Contents

  1.  Startup Class
  2. Configure() Method
  3. Middleware
  4. Using Middleware
  5. Parameter IApplicationBuilder of Configure Method
  6. Extension Methods -- Middleware provided by Microsoft

1. Startup Class

ASP.NET Core applications use the Startup  class, conventionally named Startup .  Startup  class:

  • May optionally include the ConfigureServices  method to configure the application's services.
  • Must include the Configure  method to create the application's request handling pipeline.

When the application starts, the runtime calls ConfigureServices  and Configure.

The body of Startup method is as follows

public class Startup
{
    // Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
        ...
    }
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Use this method to configure the HTTP request pipeline</span>
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> Configure(IApplicationBuilder app)
{
    ...
}

}

This article only discusses Configure


2. Configure() Method

Configure  is a method defined in

  • the namespace Microsoft.AspNetCore.Hosting 
  • an abstract class ↓↓↓
public abstract void Configure (Microsoft.AspNetCore.Builder.IApplicationBuilder app);

IApplicationBuilder

IApplicationBuilder defines a class used to configure the application's request pipeline, which consists of a series of request delegates that are invoked in order.

For readers who are unclear about the ASP.NET Core request pipeline and middleware, this part can be referenced

https://www.cnblogs.com/stulzq/p/7760648.html

https://www.cnblogs.com/JNLightGade/p/5737485.html

 

Common middleware order

  1. Exception/Error Handling
  2. HTTP Strict Transport Security
  3. HTTPS Redirection
  4. Static File Server
  5. Cookie Policy Enforcement
  6. Authentication
  7. Session
  8. MVC

You can add other parameters to override the Configure method, such as IHostingEnvironment  and ILoggerFactory

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ... ... , ... ...)
        {
        ... ...
        }

3. Middleware

The Configure method uses IApplicationBuilder to utilize middleware

There are three ways to use: Use, Map, Run

  • Use to configure middleware in the request pipeline
  • Map to branch the pipeline
  • Run to short-circuit the pipeline

For more information on this part, see

https://www.cnblogs.com/stulzq/p/7760648.html

https://www.cnblogs.com/JNLightGade/p/5737485.html

Asp.Net Core has built-in many middleware components that users can directly use, which will be introduced later in the article.


4. Using Middleware

By default, when creating an Asp.Net Core MVC application, the following template is generated (Asp.Net Core 2.1)

Later in the article, all middleware will be listed and explained in detail.

       public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();    // Development environment check
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");  // Redirect to /Error page on error
                app.UseHsts();    // Explanation found in line 39 of the article
            }
        <span style="background-color: #ffff00;">app.UseHttpsRedirection();    // Redirect HTTP to HTTPS</span>
        <span style="background-color: #ffff00;">app.UseStaticFiles();       // Use static files</span>
        <span style="background-color: #ffff00;">app.UseCookiePolicy();      // Related to cookies</span>

        <span style="background-color: #ffff00;">app.UseMvc(routes </span></span><span style="background-color: #ffff00;">=&gt;       // Use MVP pages</span><span style="color: #000000;">
        {
            routes.MapRoute(
                name: </span><span style="color: #800000;">"</span><span style="color: #800000;">default</span><span style="color: #800000;">"</span><span style="color: #000000;">,
                template: </span><span style="color: #800000;">"</span><span style="color: #800000;">{controller=Home}/{action=Index}/{id?}</span><span style="color: #800000;">"</span><span style="color: #000000;">);
        });
    }</span></pre>

You can directly use app.Use_______ format to use built-in middleware.


5. The parameter IApplicationBuilder of Configure Method

The Configure method configures the request pipeline using IApplicationBuilder. Below, the default methods, parameters, features, etc., of IApplicationBuilder will be detailed.

Properties

ApplicationServices

Gets or sets the IServiceProvider that provides access to the application service container.

IServiceProvider: Defines a mechanism for retrieving service objects, i.e., objects that provide custom support to other objects.

See also https://www.cnblogs.com/watermoon2/p/5075002.html

Properties

Gets a key/value collection that can be used to share data between middleware.

Properties is of type IDictionary<string,object>.

ServerFeatures

Gets the HTTP feature collection provided by the application server.

Click  IFeatureCollection for more details.


Methods

Build()

Builds the delegate used by this application to handle HTTP requests.

Build is a delegate of type AspNetCore.Http.RequestDelegate.

New()

Creates a new IApplicationBuilder that shares the Properties of the existing IApplicationBuilder.

Use(Func<RequestDelegate,RequestDelegate>)

Adds a middleware delegate to the application's request pipeline. Use this method for custom middleware.


6, Extension Methods -- Middleware Provided by Microsoft

Using method app._______

The following lists all middleware and their overloads, along with descriptions.

Note that the IApplicationBuilder scope is extensive, including application startup, dependency injection, routing, environment, configuration, options, logging, error handling, etc.

UseRequestLocalization(IApplicationBuilder)

Adds the RequestLocalizationMiddleware to automatically set the request's locale information based on client-provided information.

UseRequestLocalization(IApplicationBuilder, RequestLocalizationOptions)

Adds the RequestLocalizationMiddleware to automatically set the request's locale information based on client-provided information.

UseRequestLocalization(IApplicationBuilder, Action<RequestLocalizationOptions>)

Adds the RequestLocalizationMiddleware to automatically set the request's locale information based on client-provided information.

UseRequestLocalization(IApplicationBuilder, String[])

Adds the RequestLocalizationMiddleware to automatically set the request's locale information based on client-provided information.

UseAuthentication(IApplicationBuilder)

Adds the AuthenticationMiddleware to the specified IApplicationBuilder, which supports authentication features.

UseBrowserLink(IApplicationBuilder)

This method is called to enable Browser Link in the application. It registers a method factory that creates BrowserLinkMiddleware for each request.

Note:

Browser Link is a feature in Visual Studio that creates a communication channel between the development environment and one or more web browsers.You can use Browser Link to refresh web applications in multiple browsers simultaneously, which is useful for cross-browser testing.

UseIdentity(IApplicationBuilder)

This method is obsolete and will be removed in future versions.

推荐的替代方案是使用 UseAuthentication (在列表的第5行)

UseConnections(IApplicationBuilder, Action<ConnectionsRouteBuilder>)

Requests the IApplicationBuilder to add support for ASP.NET Core connection handlers to the execution pipeline

UseCookieAuthentication(IApplicationBuilder)

Deprecated and not recommended for use. Officially advised to use identity configuration (as mentioned in line 5 of the list)

UseCookieAuthentication(IApplicationBuilder, CookieAuthenticationOptions)

Deprecated and not recommended for use. Officially advised to use identity configuration (as mentioned in line 5 of the list)

UseCookiePolicy(IApplicationBuilder)

Adds the CookiePolicyMiddleware handler to the specified IApplicationBuilder, supporting cookie policy functionality

UseCookiePolicy(IApplicationBuilder, CookiePolicyOptions)

Adds the CookiePolicyMiddleware handler to the specified IApplicationBuilder, supporting cookie policy functionality

UseCors(IApplicationBuilder)

Adds the CORS middleware to the web application pipeline to allow cross-origin requests

This is a static method of type Microsoft.AspNetCore.Builder.IApplicationBuilder

UseCors(IApplicationBuilder, Action<CorsPolicyBuilder>)

Adds the CORS middleware to the web application pipeline to allow cross-origin requests

This is a static method of type Microsoft.AspNetCore.Builder.IApplicationBuilder

UseCors(IApplicationBuilder, String)

Adds the CORS middleware to the web application pipeline to allow cross-origin requests

This is a static method of type Microsoft.AspNetCore.Builder.IApplicationBuilder

UseDefaultFiles(IApplicationBuilder)

Enables default file mapping for the specified request path

UseDefaultFiles(IApplicationBuilder, DefaultFilesOptions)

Enables default file mapping for the specified request path

  Author's Note:

    The parameter DefaultFilesOptions selects options for default file names, type is DefaultFilesOptions

    Returns IApplicationBuilder

UseDefaultFiles(IApplicationBuilder, String)

Enables default file mapping for the specified request path

  Author's Note:

    The parameter String is the relative request path

    Returns IApplicationBuilder

UseDeveloperExceptionPage(IApplicationBuilder)

Catches synchronous and asynchronous exception instances from the pipeline and generates HTML error responses

UseDeveloperExceptionPage(IApplicationBuilder, DeveloperExceptionPageOptions)

Catches synchronous and asynchronous exception instances from the pipeline and generates HTML error responses

UseDirectoryBrowser(IApplicationBuilder)

Enables directory browsing on the current path

Author's Note:

For non-executable directories or special directories, users will see the directory contents when they browse to that directory in a browser.

UseDirectoryBrowser(IApplicationBuilder, DirectoryBrowserOptions)

Enables directory browsing on the current path, same as above

UseDirectoryBrowser(IApplicationBuilder, String)

Enables directory browsing on the current path, same as above

UseExceptionHandler(IApplicationBuilder)

Adds middleware to the pipeline that captures exceptions, logs the exceptions, and re-executes requests in a fallback pipeline

。如果响应已经启动,请求将不被重新执行

UseExceptionHandler(IApplicationBuilder, ExceptionHandlerOptions)

Adds middleware to the pipeline that will catch exceptions, log them, and re-execute the request in a fallback pipeline. If the response has already started, the request will not be re-executed.

UseExceptionHandler(IApplicationBuilder, Action<IApplicationBuilder>)

Adds middleware to the pipeline that will catch exceptions, log them, and re-execute the request in a fallback pipeline. If the response has already started, the request will not be re-executed.

UseExceptionHandler(IApplicationBuilder, String)

Adds middleware to the pipeline that will catch exceptions, log them, and re-execute the request in a fallback pipeline. If the response has already started, the request will not be re-executed.

UseFacebookAuthentication(IApplicationBuilder)

Uses Facebook authentication.

UseFacebookAuthentication(IApplicationBuilder, FacebookOptions)

Uses Facebook authentication.

UseFileServer(IApplicationBuilder)

Enables all static file middleware (excluding directory browsing) for the current request path in the current directory. -- Note the differences among the four variants.

UseFileServer(IApplicationBuilder, FileServerOptions)

Uses the given options for all static file middleware. -- Note the differences among the four variants.

UseFileServer(IApplicationBuilder, Boolean)

Indicates whether to enable all static file middleware (excluding directory browsing) for the current request path in the current directory. -- Note the differences among the four variants.

UseFileServer(IApplicationBuilder, String)

Enables all static file middleware (excluding directory browsing) for the given request path from a directory with the same name. -- Note the differences among the four variants.

UseForwardedHeaders(IApplicationBuilder)

Forwards proxy to the current request headers.

UseForwardedHeaders(IApplicationBuilder, ForwardedHeadersOptions)

Forwards proxy to the current request headers.

UseGoogleAuthentication(IApplicationBuilder)

Uses Google for authentication.

UseGoogleAuthentication(IApplicationBuilder, GoogleOptions)

Uses Google for authentication.

UseHostFiltering(IApplicationBuilder)

Adds middleware that filters requests based on allowed host headers; invalid requests are rejected with a 400 status code.

UseHsts(IApplicationBuilder)

Adds middleware that enables HSTS by adding strict transport security headers.

UseHttpMethodOverride(IApplicationBuilder)

Allows incoming POST requests to override the method type specified in the header.

UseHttpMethodOverride(IApplicationBuilder, HttpMethodOverrideOptions)

Allows incoming POST requests to override the method type as specified in the form.

UseHttpsRedirection(IApplicationBuilder)

Adds middleware for redirecting HTTP requests to HTTPS.

</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.jwtbearerappbuilderextensions.usejwtbearerauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_JwtBearerAppBuilderExtensions_UseJwtBearerAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseJwtBearerAuthentication(IApplicationBuilder)</a></span></td>
<td>
<p>UseJwtBearerAuthentication is a deprecated authentication scheme and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.jwtbearerappbuilderextensions.usejwtbearerauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_JwtBearerAppBuilderExtensions_UseJwtBearerAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Authentication_JwtBearer_JwtBearerOptions_" data-linktype="relative-path">UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)</a></span></td>
<td>
<p>UseJwtBearerAuthentication is a deprecated authentication scheme and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.mapextensions.map?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_MapExtensions_Map_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Http_PathString_System_Action_Microsoft_AspNetCore_Builder_IApplicationBuilder__" data-linktype="relative-path">Map(IApplicationBuilder, PathString, Action&lt;IApplicationBuilder&gt;)</a></span></td>
<td>
<p>Branches the request pipeline based on a match of the given request path. If the request path starts with the given path, the branch is executed.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.mapwhenextensions.mapwhen?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_MapWhenExtensions_MapWhen_Microsoft_AspNetCore_Builder_IApplicationBuilder_System_Func_Microsoft_AspNetCore_Http_HttpContext_System_Boolean__System_Action_Microsoft_AspNetCore_Builder_IApplicationBuilder__" data-linktype="relative-path">MapWhen(IApplicationBuilder, Func&lt;HttpContext,Boolean&gt;, Action&lt;IApplicationBuilder&gt;)</a></span></td>
<td>
<p>Branches the request pipeline based on the results of a given prediction.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.microsoftaccountappbuilderextensions.usemicrosoftaccountauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_MicrosoftAccountAppBuilderExtensions_UseMicrosoftAccountAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseMicrosoftAccountAuthentication(IApplicationBuilder)</a></span></td>
<td>
<p>UseMicrosoftAccountAuthentication is deprecated and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.microsoftaccountappbuilderextensions.usemicrosoftaccountauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_MicrosoftAccountAppBuilderExtensions_UseMicrosoftAccountAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Authentication_MicrosoftAccount_MicrosoftAccountOptions_" data-linktype="relative-path">UseMicrosoftAccountAuthentication(IApplicationBuilder, MicrosoftAccountOptions)</a></span></td>
<td>
<p>UseMicrosoftAccountAuthentication is deprecated and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.mvcapplicationbuilderextensions.usemvc?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_MvcApplicationBuilderExtensions_UseMvc_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseMvc(IApplicationBuilder)</a></span></td>
<td>
<p>Adds MVC to the request execution pipeline.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.mvcapplicationbuilderextensions.usemvc?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_MvcApplicationBuilderExtensions_UseMvc_Microsoft_AspNetCore_Builder_IApplicationBuilder_System_Action_Microsoft_AspNetCore_Routing_IRouteBuilder__" data-linktype="relative-path">UseMvc(IApplicationBuilder, Action&lt;IRouteBuilder&gt;)</a></span></td>
<td>
<p>Adds MVC to the request execution pipeline and configures routing, using the example.</p>
<pre class="brush:csharp;gutter:true;">app.UseMvc(routes =&gt;
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });</pre>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.mvcapplicationbuilderextensions.usemvcwithdefaultroute?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_MvcApplicationBuilderExtensions_UseMvcWithDefaultRoute_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseMvcWithDefaultRoute(IApplicationBuilder)</a></span></td>
<td>
<p>Uses the default routing template.</p>
<p>Note from the author:</p>
<p>When you create an MVC application, the default routing template is already generated.</p>
<p>The default routing template format is <span style="background-color: #ffff00;">&nbsp;{controller=Home}/{action=Index}/{id?}&nbsp;</span></p>
<p><span style="background-color: #ffffff;">Using this middleware is equivalent to the example in the previous table.</span></p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.oauthappbuilderextensions.useoauthauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_OAuthAppBuilderExtensions_UseOAuthAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseOAuthAuthentication(IApplicationBuilder)</a></span></td>
<td>
<p>UseOAuthAuthentication is deprecated and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.oauthappbuilderextensions.useoauthauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_OAuthAppBuilderExtensions_UseOAuthAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Authentication_OAuth_OAuthOptions_" data-linktype="relative-path">UseOAuthAuthentication(IApplicationBuilder, OAuthOptions)</a></span></td>
<td>
<p>UseOAuthAuthentication is deprecated and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.openidconnectappbuilderextensions.useopenidconnectauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_OpenIdConnectAppBuilderExtensions_UseOpenIdConnectAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseOpenIdConnectAuthentication(IApplicationBuilder)</a></span></td>
<td>
<p>UseOpenIdConnectAuthentication is deprecated and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.openidconnectappbuilderextensions.useopenidconnectauthentication?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_OpenIdConnectAppBuilderExtensions_UseOpenIdConnectAuthentication_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Authentication_OpenIdConnect_OpenIdConnectOptions_" data-linktype="relative-path">UseOpenIdConnectAuthentication(IApplicationBuilder, OpenIdConnectOptions)</a></span></td>
<td>
<p>UseOpenIdConnectAuthentication is deprecated and is no longer recommended by the official documentation.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-1.1 aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.responsecompressionbuilderextensions.useresponsecompression?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_ResponseCompressionBuilderExtensions_UseResponseCompression_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseResponseCompression(IApplicationBuilder)</a></span></td>
<td>
<p>Adds middleware for dynamically compressing HTTP responses.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.rewritebuilderextensions.userewriter?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_RewriteBuilderExtensions_UseRewriter_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseRewriter(IApplicationBuilder)</a></span></td>
<td>
<p>Checks if a given URL matches specific rules and conditions (regular expressions) and modifies the matching HTTP context.</p>
</td>
</tr>

。</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-1.1 aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.rewritebuilderextensions.userewriter?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_RewriteBuilderExtensions_UseRewriter_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Rewrite_RewriteOptions_" data-linktype="relative-path">UseRewriter(IApplicationBuilder, RewriteOptions)</a></span></td>
<td>
<p>Checks if the given URL matches the rules and conditions (regular expressions) and modifies the matching HTTP context.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.routingbuilderextensions.userouter?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_RoutingBuilderExtensions_UseRouter_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Routing_IRouter_" data-linktype="relative-path">UseRouter(IApplicationBuilder, IRouter)</a></span></td>
<td>
<p>Creates routing rules and adds them to the routing table.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-1.1 aspnetcore-2.0 aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.routingbuilderextensions.userouter?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_RoutingBuilderExtensions_UseRouter_Microsoft_AspNetCore_Builder_IApplicationBuilder_System_Action_Microsoft_AspNetCore_Routing_IRouteBuilder__" data-linktype="relative-path">UseRouter(IApplicationBuilder, Action&lt;IRouteBuilder&gt;)</a></span></td>
<td>
<p>Creates routing rules and adds them to the routing table.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.runextensions.run?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_RunExtensions_Run_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Http_RequestDelegate_" data-linktype="relative-path">Run(IApplicationBuilder, RequestDelegate)</a></span></td>
<td>
<p>Short-circuits the pipeline.</p>
<p>Author's note:</p>
<p>When the pipeline encounters Run, it will ignore any other middleware that follows, regardless of whether it exists or not.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.sessionmiddlewareextensions.usesession?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_SessionMiddlewareExtensions_UseSession_Microsoft_AspNetCore_Builder_IApplicationBuilder_" data-linktype="relative-path">UseSession(IApplicationBuilder)</a></span></td>
<td>
<p>Adds session to automatically enable session state for the application.</p>
</td>
</tr>
<tr>
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.sessionmiddlewareextensions.usesession?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_SessionMiddlewareExtensions_UseSession_Microsoft_AspNetCore_Builder_IApplicationBuilder_Microsoft_AspNetCore_Builder_SessionOptions_" data-linktype="relative-path">UseSession(IApplicationBuilder, SessionOptions)</a></span></td>
<td>
<p>Adds session to automatically enable session state for the application.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.signalrappbuilderextensions.usesignalr?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_SignalRAppBuilderExtensions_UseSignalR_Microsoft_AspNetCore_Builder_IApplicationBuilder_System_Action_Microsoft_AspNetCore_SignalR_HubRouteBuilder__" data-linktype="relative-path">UseSignalR(IApplicationBuilder, Action&lt;HubRouteBuilder&gt;)</a></span></td>
<td>
<p>Adds SignalR to the request pipeline.</p>
</td>
</tr>
<tr data-moniker=" aspnetcore-2.1 ">
<td><span class="lang-csharp"><a class="xref" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.spaapplicationbuilderextensions.usespa?view=aspnetcore-2.1#Microsoft_AspNetCore_Builder_SpaApplicationBuilderExtensions_UseSpa_Microsoft_AspNetCore_Builder_IApplicationBuilder_System_Action_Microsoft_AspNetCore_SpaServices_ISpaBuilder__" data-linktype="relative-path">UseSpa(IApplicationBuilder, Action&lt;ISpaBuilder&gt;)</a></span></td>
<td>
<p>Through returning the default page of a single-page application (SPA), handles all requests starting from this point in the middleware chain.</p>

这个中间件应该放在链的末尾,以便其他提供静态文件、MVC操作等的中间件优先

| 代码 | 描述 |
|------|------|
| UseStaticFiles(IApplicationBuilder) | 为当前请求路径启用静态文件服务 |
| UseStaticFiles(IApplicationBuilder, StaticFileOptions) | 为当前请求路径启用静态文件服务 |
| UseStaticFiles(IApplicationBuilder, String) | 为当前请求路径启用静态文件服务 |
| UseStatusCodePages(IApplicationBuilder) | 添加具有默认响应处理程序的中间件,该处理程序检查400和599之间没有主体时的状态代码,以进行响应 |
| UseStatusCodePages(IApplicationBuilder, StatusCodePagesOptions) | 同上 |
| UseStatusCodePages(IApplicationBuilder, Action<IApplicationBuilder>) | 同上 |
| UseStatusCodePages(IApplicationBuilder, Func<StatusCodeContext,Task>) | 同上 |
| UseStatusCodePages(IApplicationBuilder, String, String) | 同上 |
| UseStatusCodePagesWithRedirects(IApplicationBuilder, String) | 同上 |
| UseStatusCodePagesWithReExecute(IApplicationBuilder, String, String) | 同上 |
| UseTwitterAuthentication(IApplicationBuilder) | 使用 Twitter 进行身份认证,官方不再推荐这种过时用法 |
| UseTwitterAuthentication(IApplicationBuilder, TwitterOptions) | 使用 Twitter 进行身份认证,官方不再推荐这种过时用法 |
| Use(IApplicationBuilder, Func<HttpContext,Func<Task>,Task>) | 将一个中间件委托添加到应用程序的请求管道中 |
| UseMiddleware(IApplicationBuilder, Type, Object[]) | 将一个中间件添加到应用程序的请求管道中,注意与上面的区别 |
| UseMiddleware<TMiddleware>(IApplicationBuilder, Object[]) | 将一个中间件添加到应用程序的请求管道中,注意与上面的区别 |
| UsePathBase(IApplicationBuilder, PathString) | 加中间件,从中间件从请求路径中提取指定的路径库并将其附加到请求路径库 |
| UseWhen(IApplicationBuilder, Func<HttpContext,Boolean>, Action<IApplicationBuilder>) | 有条件地在请求管道中创建一个分支,并将其重新连接到主管道 |
| UseWebpackDevMiddleware(IApplicationBuilder, WebpackDevMiddlewareOptions) | Enables Webpack dev middleware support. This hosts an instance of the Webpack compiler in memory in your application so that you can always serve up-to-date Webpack-built resources without having to run the compiler manually. Since the Webpack compiler instance is retained in memory, incremental compilation is vastly faster than re-running the compiler from scratch. Incoming requests that match Webpack-built files will be handled by re |

turning the Webpack compiler output directly, regardless of files on disk. If compilation is in progress when the request arrives, the response will pause until updated compiler output is ready.

UseWebSockets(IApplicationBuilder)

WebSockets service

UseWebSockets(IApplicationBuilder, WebSocketOptions)

WebSockets service

UseWelcomePage(IApplicationBuilder)

Add a welcome page to the request pipeline

UseWelcomePage(IApplicationBuilder, WelcomePageOptions)

Add a welcome page to the request pipeline with custom welcome page configuration

UseWelcomePage(IApplicationBuilder, PathString)

Add a welcome page to the request pipeline with a custom welcome page path

UseWelcomePage(IApplicationBuilder, String)

Add a welcome page to the request pipeline

UseSpaStaticFiles(IApplicationBuilder)

Configure the application to serve static files for single-page applications (SPA)

UseSpaStaticFiles(IApplicationBuilder, StaticFileOptions)

Configure the application to serve static files for single-page applications (SPA)

痴者工良

高级程序员劝退师

文章评论