.net core 中间件实战
1、新建一个ASP.NET Core Web Application项目,选择空模板。


2、新建一个类RequestIPMiddleware.cs
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MiddlewareDemo
{
public class RequestIPMiddleware
{
private readonly RequestDelegate _next;
public RequestIPMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
await context.Response.WriteAsync("to do something \n\r");
await context.Response.WriteAsync("IP:" + context.Connection.RemoteIpAddress.ToString() + "\n\r");
await _next.Invoke(context);
}
}
}
3、再新建一个扩展类 RequestIPExtensions.cs
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MiddlewareDemo
{
public static class RequestIPExtensions
{
public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestIPMiddleware>();
}
}
}
4、使用中间件。在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 MiddlewareDemo
{
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.UseRequestIP();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
5、运行效果

浙公网安备 33010602011771号