[Asp.net core]自定义中间件
2017-09-28 10:39
886 查看
我们知道在asp.net中每次请求,都要经过请求管道,依次触发管道中的一系列事件。那么我们可以这么理解,中间件是请求管道中的一个组件,可以用来拦截请求,以方便我们进行请求和响应处理,中间件可以定义多个,每一个中间件都可以对管道中的请求进行拦截,它可以决定是否将请求转移给下一个中间件。
大概有3种方式可以在管道中注册"中间件"
上面的Run,Map内部也是调用的Use,算是对IApplicationBuilder接口扩充,如果你觉得名字都不够准确,那么下面这个扩展方法就是正宗的注册中间件的了,也是功能最强大的
asp.net core 提供了
该如何使用我们定义的中间件?
在startup.cs中启用中间件
直接运行程序
以这种方式运行程序,是以使用Kestrel为宿主服务器运行的。
运行结果
中间件如何工作?
默认情况下,中间件的执行顺序根据Startup.cs文件中,在
public void Configure(IApplicationBuilder app){}方法中注册的先后顺序执行。
大概有3种方式可以在管道中注册"中间件"
app.Use(),
IApplicationBuilder接口原生提供,注册等都用它。
app.Run(),是一个扩展方法,它需要一个
RequestDelegate委托,里面包含了Http的上下文信息,没有next参数,因为它总是在管道最后一步执行。
app.Map(),也是一个扩展方法,类似于MVC的路由,用途一般是一些特殊请求路径的处理。如:www.example.com/token 等。
上面的Run,Map内部也是调用的Use,算是对IApplicationBuilder接口扩充,如果你觉得名字都不够准确,那么下面这个扩展方法就是正宗的注册中间件的了,也是功能最强大的
app.UseMiddleware<>(), 为什么说功能强大呢?是因为它不但提供了注册中间件的功能,还提供了依赖注入(DI)的功能,以后大部分情况就用它了。
asp.net core 提供了
IApplicationBuilder接口来让把中间件注册到asp.net的管道请求当中去。那么我们现在自定义一个中间件的功能,比如打印请求的客户端ip功能。
自定义中间件
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Wolfy.IPDemo.Middlewares { // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project public class IPMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public IPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) { _next = next; _logger = loggerFactory.CreateLogger<IPMiddleware>(); } public Task Invoke(HttpContext httpContext) { _logger.LogInformation($"Client Ip:{httpContext.Connection.RemoteIpAddress.ToString()}"); return _next(httpContext); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class IPMiddlewareExtensions { public static IApplicationBuilder UseIP(this IApplicationBuilder builder) { return builder.UseMiddleware<IPMiddleware>(); } } }
该如何使用我们定义的中间件?
在startup.cs中启用中间件
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 http://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, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); app.UseIP(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } }
直接运行程序
以这种方式运行程序,是以使用Kestrel为宿主服务器运行的。
运行结果
总结
本篇文章介绍了,如何自定义中间件,以及如何使用定义的中间件,那么在什么场景下使用中间件?个人认为,如果和业务关系不大的功能,可以定义为中间件,方便使用。相关文章推荐
- ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介
- ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介
- ASP.NET Core 1.1 静态文件、路由、自定义中间件、身份验证简介
- ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介
- Asp.Net Core 通过自定义中间件防止图片盗链的实例(转)
- asp.net core 自定义中间件和service
- ASP.NET CORE 自定义视图组件(ViewComponent)注意事项
- 在ASP.NET Core 中使用Cookie中间件
- ASP.NET Core真实管道详解[1]:中间件是个什么东西?
- ASP.NET Core 使用 URL Rewrite 中间件实现 HTTP 重定向到 HTTPS
- 详解ASP.NET Core 中间件之压缩、缓存
- 在ASP.NET Core中实现自定义验证特性(Custom Validation Attribute)
- ASP.NET Core自定义本地化教程之从文本文件读取本地化字符串
- ASP.NET Core 中的中间件
- ASP.NET Core 运行原理剖析2:Startup 和 Middleware(中间件)
- [dotnetCore2.0]学习笔记之二: ASP.NET Core中,如何灵活使用静态文件和加载自定义配置
- ASP.NET Core使用自定义验证属性控制访问权限详解
- ASP.NET Core应用针对静态文件请求的处理[5]: DefaultFilesMiddleware中间件如何显示默认页面
- ASP.NET MVC随想录——创建自定义的Middleware中间件
- [译]ASP.NET Core 2.0 中间件