1. 程式人生 > >[Asp.net core]自定義中間件

[Asp.net core]自定義中間件

actions app {} 處理 cli 服務器 space cat es2017

我們知道在asp.net中每次請求,都要經過請求管道,依次觸發管道中的一系列事件。那麽我們可以這麽理解,中間件是請求管道中的一個組件,可以用來攔截請求,以方便我們進行請求和響應處理,中間件可以定義多個,每一個中間件都可以對管道中的請求進行攔截,它可以決定是否將請求轉移給下一個中間件。

中間件如何工作?

默認情況下,中間件的執行順序根據Startup.cs文件中,在public void Configure(IApplicationBuilder app){} 方法中註冊的先後順序執行。
大概有3種方式可以在管道中註冊"中間件"

  1. app.Use()IApplicationBuilder
    接口原生提供,註冊等都用它。
  2. app.Run() ,是一個擴展方法,它需要一個RequestDelegate委托,裏面包含了Http的上下文信息,沒有next參數,因為它總是在管道最後一步執行。
  3. app.Map(),也是一個擴展方法,類似於MVC的路由,用途一般是一些特殊請求路徑的處理。如:www.example.com/token 等。

上面的Run,Map內部也是調用的Use,算是對IApplicationBuilder接口擴充,如果你覺得名字都不夠準確,那麽下面這個擴展方法就是正宗的註冊中間件的了,也是功能最強大的
app.UseMiddleware<>(), 為什麽說功能強大呢?是因為它不但提供了註冊中間件的功能,還提供了依賴註入(DI)的功能,以後大部分情況就用它了。

asp.net core 提供了IApplicationBuilder接口來讓把中間件註冊到asp.net的管道請求當中去。那麽我們現在自定義一個中間件的功能,比如打印請求的客戶端ip功能。

自定義中間件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Wolfy.IPDemo.Middlewares { // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project public class IPMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public IPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) { _next = next; _logger = loggerFactory.CreateLogger<IPMiddleware>(); } public Task Invoke(HttpContext httpContext) { _logger.LogInformation($"Client Ip:{httpContext.Connection.RemoteIpAddress.ToString()}"); return _next(httpContext); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class IPMiddlewareExtensions { public static IApplicationBuilder UseIP(this IApplicationBuilder builder) { return builder.UseMiddleware<IPMiddleware>(); } } }

該如何使用我們定義的中間件?

在startup.cs中啟用中間件

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            app.UseIP();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

直接運行程序

技術分享

以這種方式運行程序,是以使用Kestrel為宿主服務器運行的。

運行結果

技術分享

總結

本篇文章介紹了,如何自定義中間件,以及如何使用定義的中間件,那麽在什麽場景下使用中間件?個人認為,如果和業務關系不大的功能,可以定義為中間件,方便使用。

[Asp.net core]自定義中間件