版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ITzhongzi/article/details/80883935
目的: 创建一个在接收到请求之后,将请求的地址打印在后台服务器窗口上的中间件
注意: 该项目是通过 vs2017 新建项目-> Net Core -> ASP.NET Web应用程序 -> 空 模板 初始化
- 创建一个 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>();
}
}
}
- 创建一个 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);
}
}
}
- 接下来我们在 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!");
});
}
}
}
- 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。