首先要明确什么是中间件?微软官方解释:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?tabs=aspnetcore2x

也就是中,我们需要在整个应用程序的请求管道中注入某一个中间层来做我们想做的事情。谈谈我的理解:
就拿asp.net 的管道模型来说,以往的.net请求管道中我们知道有21个(应该不止)事件来分别处理相应的模块,这是微软为我们设计好的,如果我们需要拓展出来什么,在相应的事件中写入注册就可以了。但是现在的软件设计模型逐渐的加入了一层---中间件,在整个的应用程序请求管道,我们不做任何的事件封装,而是开放出来,由程序猿自己在某个应用程序的某个部分写入自己需要注入的,而且可以注入多个,但是顺序什么的就是由自己定义了。
那么我们就需要基于IApplicationBuilder来构建我们的中间件。在哪个方法里面调用呢?那必须是Configure方法。根据微软官方的解释:Configure 方法用于指定如何响应HTTP 请求。在这里我们需要使用微软的UseMiddleware<T> 拓展方法来构建我们的中间件(每个Use扩展方法将中间件组件添加到请求管道)。我们将中间件封装在类中,并且通过扩展方法公开。封装如下:

public class RequestCultureMiddleware
{
private readonly RequestDelegate _next; public RequestCultureMiddleware(RequestDelegate next)
{
_next = next;
} public Task InvokeAsync(HttpContext context)
{
var cultureQuery = context.Request.Query["culture"];
if (!string.IsNullOrWhiteSpace(cultureQuery))
{
var culture = new CultureInfo(cultureQuery); CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture; } // Call the next delegate/middleware in the pipeline
return _next(context);
} }

接着我们基于IApplicationBuilder接口拓展我们的中间件。通过UseMiddleware 来使用中间件。

public static class RequestCultureMiddlewareExtensions
{
public static IApplicationBuilder UseRquestCulture(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestCultureMiddleware>();
}
}

最后我们在Configure中使用我们的中间件:

// 自定义中间件.
app.UseRquestCulture();

一般来讲,我们是在ConfigureServices 方法中注册服务,然后在Configure 方法中使用,但是
Configgure 方法可使用IApplicationBuilder实例来配置请求管道,不需要再服务容器重注册。当然我们也可以那么做,请参看: https://github.com/aspnet/Docs/tree/master/aspnetcore/fundamentals/startup/sample

中间件分析及三种实现方式:ASP.NET Core Middleware

最新文章

  1. Linux &amp; Systemd 挂载问题解决
  2. java根据逗号分隔字符串,后加上单引号
  3. mac平台下面nodejs环境搭配
  4. TextView的属性列表
  5. MongoDB 快速入门--中级
  6. qt容器在并发时需要注意的地方
  7. cf B. Road Construction
  8. React-Native 之 项目实战(五)
  9. 【模板小程序】求M~N范围内的质数个数
  10. [Reinforcement Learning] Model-Free Control
  11. 修改host,上github
  12. Python01(linux基础)
  13. LAMP架构
  14. Linux磁盘空间分析及清理(df、du、rm)
  15. 获取本机的ip地址(排除虚拟机,蓝牙等ip)
  16. linux下locale中的各环境变量的含义
  17. 8 云计算系列之Horizon的安装与虚拟机创建流程
  18. Java String源码解析
  19. 【题解】洛谷P3200 [HNOI2009] 有趣的数列(卡特兰数+质因数分解)
  20. 使用instsrv.exe和srvany.exe将应用程序安装成windows后台服务

热门文章

  1. 怎样在Ubuntu 14.04中搭建gitolite git服务器
  2. 利用cocos2d-x实现CandyCrushSaga消除功能
  3. Hibernate配置文件current_session_context_class的意思
  4. TCP协议三次握手与四次挥手详解
  5. 后端分布式系列:分布式存储-HDFS Client 设计实现解析
  6. 【一天一道LeetCode】#122. Best Time to Buy and Sell Stock II
  7. 95%的bug是由程序员造成的
  8. sed在行首或者行尾添加内容
  9. Linux之使用网络
  10. lua c函数注册器