.net Core中间件实战
新建一个ASP.NET Core Web Application 项目选中空模板
然后为项目添加一个Microsoft.Extensions.Logging.Console
由于我用的.net core1.1 则选择对应1.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 xzyCore { 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); } } }
然后在创建一个RequestIPExtensions.cs
using Microsoft.AspNetCore.Builder; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace xzyCore { public static class RequestIPExtensions { public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestIPMiddleware>(); } } }
这样就编写好一个中间件了。
在Startup.cs中添加app.UseRequestIP();
// 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.UseRequestIP(); if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); }
然后在运行程序
成功运行,这里我们还可以对这个中间件进行进一步改进,增加更多的功能,如限制访问等。