.Net Core中的中间件实战
电脑版发表于:2019/3/3 18:40
什么是中间件?
凡是app点出来的都是中间件,如下图所示
今天就来制作一下中间件
1,创建一个.netcore的web空项目
2,创建一个RequesIPMiddleware类
public class RequesIPMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public RequesIPMiddleware(RequestDelegate next ,ILoggerFactory logger) { _next = next; _logger = logger.CreateLogger<RequesIPMiddleware>(); } /// <summary> /// 执行的方法 /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Invoke(HttpContext context) { //执行超作 _logger.LogInformation("My Ip:" + context.Connection.RemoteIpAddress.ToString()); //执行下一个中间件 await _next.Invoke(context); } }
3,创建一个RequestPExtensions.cs类
public static class RequestPExtensions { public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder) { return builder.UseMiddleware<RequesIPMiddleware>(); } }
这样一个中间件就算完成了!
4,调用中间件 UseRequestIP
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory iLoggerFactory) { iLoggerFactory.AddConsole(minLevel: LogLevel.Information); app.UseRequestIP(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); }
运行(由于我这里是本地运行so这里ip就成这样了):
感谢各位老铁的观看!