1 与ASP .NET MVC
- ASP .NET MVC 就是UrlRoutingModule 实现了url请求的拦截。
- ASP .NET Core 的Pipeline 更加轻量化,模块化
- 改变了HttpModule的事件模式,单链表(递归) next方法
2 理解
![](https://img.haomeiwen.com/i7983343/de442549c82530b0.png)
RequestDelegate
-
ApplicationBuilder
_compennents
Run 方法
2.png
调用Use
![](https://img.haomeiwen.com/i7983343/d7565ee09655ca20.png)
3 使用
// 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.Use(async (context, next) =>
{
await context.Response.WriteAsync(" First Middleware Output </br>");
//此处执行 才能不中断管道
await next.Invoke();
});
app.Use(next =>
{
return (context) =>
{
context.Response.WriteAsync(" Second Middleware Output </br>");
//此处执行 才能不中断管道
return next(context);
};
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World! </br>");
});
}
4 实现自定义的Middleware
定义UserIpWhiteMiddleware
public class IpWhiteMiddleware
{
private readonly RequestDelegate _next;
public IpWhiteMiddleware(RequestDelegate next)
{
this._next = next;
}
public Task Invoke(HttpContext context)
{
var whiteList = new List<string>() {"127.0.0.1", "::1" };
var rqIp = context.Connection.RemoteIpAddress.ToString();
if (!whiteList.Any(c=>c==rqIp))
{
return context.Response.WriteAsync(" not in white ip list");
}
var task = this._next.Invoke(context);
return task;
}
}
定义IApplicationBuilder的扩展方法
public static class IpWhiteMiddlewareExtensions
{
public static IApplicationBuilder UserIpWhiteMiddleware(this IApplicationBuilder app)
{
return UseMiddlewareExtensions.UseMiddleware<IpWhiteMiddleware>(app, Array.Empty<object>());
}
}
Startup.cs
使用
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 AspNetCoreStudy.Middleware
{
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.UserIpWhiteMiddleware();
}
}
}
网友评论