1. 程式人生 > >Net Core中介軟體封裝原理示例demo解析

Net Core中介軟體封裝原理示例demo解析

目的: 建立一個在接收到請求之後,將請求的地址列印在後臺伺服器視窗上的中介軟體

注意: 該專案是通過 vs2017 新建專案-> Net Core -> ASP.NET Web應用程式 -> 空 模板 初始化 
  1. 建立一個 RequestExtensions.cs 的檔案,這個檔案用來擴充套件增加一箇中間件
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MiddlelewareDemo
{
    public
static class RequestIpExtensions { public static IApplicationBuilder UseRequestIp(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestIPMiddleware>(); } } }
  1. 建立一個 RequestIPMiddleware.cs 的檔案,這個檔案是中介軟體的具體實現(獲取遠端訪問的地址,並將該地址輸出到伺服器控制檯上)
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MiddlelewareDemo
{
    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); } } }
  1. 接下來我們在 Startup.cs 中使用該中介軟體,用 app.UseRequestIp(); 呼叫。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace MiddlelewareDemo
{
    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 https://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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseDefaultFiles();
            app.UseRequestIp();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello 0 World!");
            });
        }
    }
}
  1. Program.cs檔案的程式碼:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace MiddlelewareDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

執行效果:

這裡寫圖片描述

我們看到 中介軟體呼叫成功,在瀏覽器訪問的時候在後臺成功打印出了 IP xxxxx。