ASP.NET Core 開發-中介軟體(Middleware)

來源:互聯網
上載者:User

標籤:管道   bsp   app   connect   nbsp   startup   asp.net   href   layout   

參考頁面:

http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-layout.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-view-start.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-import-view.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-taghelpers.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-edit-form.html

ASP.NET Core開發,開發並使用中介軟體(Middleware)。

中介軟體是被組裝成一個應用程式管道來處理請求和響應的軟體組件。

每個組件選擇是否傳遞給管道中的下一個組件的請求,並能之前和下一組分在管道中調用之後執行特定操作。

具體

 

開發中介軟體(Middleware)

今天我們來實現一個記錄ip 的中介軟體。

1.建立一個asp.net core項目,選擇空的模板。

然後為項目添加一個 Microsoft.Extensions.Logging.Console

NuGet 命令列 ,請使用官方源。

Install-Package Microsoft.Extensions.Logging.Console -Pre

2.建立一個類: RequestIPMiddleware.cs

    public class RequestIPMiddleware    {        private readonly RequestDelegate _next;        private readonly ILogger _logger;        public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)        {            _next = next;            _logger = loggerFactory.CreateLogger<RequestIPMiddleware>();        }        public async Task Invoke(HttpContext context)        {                        _logger.LogInformation("User IP: " + context.Connection.RemoteIpAddress.ToString());            await _next.Invoke(context);        }    }

 

3.再建立一個:RequestIPExtensions.cs

    public static class RequestIPExtensions    {        public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)        {            return builder.UseMiddleware<RequestIPMiddleware>();        }    }

這樣我們就編寫好了一個中介軟體。

使用中介軟體(Middleware)

1.使用

在 Startup.cs 添加 app.UseRequestIP()

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)        {            loggerfactory.AddConsole(minLevel: LogLevel.Information);            app.UseRequestIP();//使用中介軟體            app.Run(async (context) =>            {                await context.Response.WriteAsync("Hello World!");            });        }

然後運行程式,我選擇使用Kestrel 。

訪問:http://localhost:5000/

成功運行。

這裡我們還可以對這個中介軟體進行進一步改進,增加更多的功能,如限制訪問等。

 

如果你覺得本文對你有協助,請點擊“推薦”,謝謝。

ASP.NET Core 開發-中介軟體(Middleware)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.