[译]Writing Custom Middleware in ASP.NET Core 1.0
原文: https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/
Middleware是ASP.NET Core 1.0的新特性。Middleware用来检测request和response的输入输出。
什么是Middleware?
Middleware是用来检测request和response的组件。Pipeline如下:

Middleware可以用来替代HttpModules和HttpHandlers的工作。
默认的Middleware
使用VS创建的ASP.NET Core的应用,默认就使用了Middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink(); //Middleware
app.UseDeveloperExceptionPage(); //Middleware
}
else
{
app.UseExceptionHandler("/Home/Error"); //Middleware
}
app.UseIISPlatformHandler(); //Middleware
app.UseStaticFiles(); //Middleware
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
}); //Middleware
}
在上面的方法中,那些app.UserX(),就意味着使用了ASP.NET默认的Middleware组件。
自定义Middleware组件
Middleware组件和其他的class基本一样, 不同的是Middleware有一个类型为RequestDelegate的私有属性,如下:
public class AuthorizationMiddleware
{
private readonly RequestDelegate _next;
public AuthorizationMiddleware(RequestDelegate next)
{
_next = next;
}
}
_next属性是一个委托,为Pipeline中下一个组件所用。 每个Middleware都实现一个async任务:
public async Task Invoke(HttpContext context)
{
await _next.Invoke(context);
}
Middleware任务
下面我们新建一个Middleware用于检查HTTP头,如果HTTP头有"X-Not-Authorized",直接返回401。代码如下:
public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.Keys.Contains("X-Not-Authorized"))
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
await _next.Invoke(context);
}
Middleware可以做许多事。例如:
- 你想检查每一次request,如果request请求的是一个图片,将请求redirect的一个图片handler。
- 你想有一个组件用来记录每一次http请求
- ..........
其他Middleware的例子
定义一个RequestHeaderMiddleware
public class RequestHeaderMiddleware
{
private readonly RequestDelegate _next;
public RequestHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.Keys.Contains("X-Cancel-Request"))
{
context.Response.StatusCode = 500;
return;
}
await _next.Invoke(context);
if (context.Request.Headers.Keys.Contains("X-Transfer-By"))
{
context.Response.Headers.Add("X-Transfer-Success", "true");
}
}
}
这个Middleware可以做两件事情:
- 如果HTTP请求头包含"X-Cancel-Request"那么服务器之间返回500
- 如果HTTP请求头包含"X-Transfer-By"服务器给响应头加上"X-Transfer-Success"
定义一个ProcessingTimeMiddleware
public class ProcessingTimeMiddleware
{
private readonly RequestDelegate _next;
public ProcessingTimeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var watch = new Stopwatch();
watch.Start();
await _next(context);
context.Response.Headers.Add("X-Processing-Time-Milliseconds", new[] { watch.ElapsedMilliseconds.ToString() });
}
}
上面的Middleware用到了Stopwatch,这个组件记录请求响应的时间,并将其作为响应头返回给客户。
添加Middeware到HTTP管道中
有两种方法将Middleware注册到pipeline中。 一种是在Startup文件的Configure方法中调用IApplicationBuilder的UseMiddleware方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseMiddleware<AuthorizationMiddleware>();
...
}
另一种是我推荐使用的方法,为每个你想注册的Middleware添加一个扩展方法,然后在Configure中调用。代码如下:
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseRequestHeaderMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestHeaderMiddleware>();
}
public static IApplicationBuilder UseAuthorizationMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AuthorizationMiddleware>();
}
public static IApplicationBuilder UseProcessingTimeMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ProcessingTimeMiddleware>();
}
}
现在可以在Starup中使用这些扩展方法了(仔细读下面的代码,它包含一个Bug)
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseProcessingTimeMiddleware();
app.UseRequestHeaderMiddleware();
app.UseAuthorizationMiddleware();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
发现这个Bug了没?
当你注册Middleware时,你添加Middleware的顺序非常重要。上面的代码中,我们首先添加了ProcessingTimeMiddleware, 然后添加RequestHeaderMiddleware,最后添加的是AuthorizationMiddleware。 这个顺序恰好搞反了。 正确的顺序如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseAuthorizationMiddleware();
app.UseRequestHeaderMiddleware();
app.UseProcessingTimeMiddleware();
...
}
总结
记住下面3点:
- Middleware能让我们完全控制Http管道
- Middleware可以处理验证,重定向,HTTP头,甚至取消HTTP请求
- 在Startup中注册Middleware的顺序非常重要
[译]Writing Custom Middleware in ASP.NET Core 1.0的更多相关文章
- [转]Writing Custom Middleware in ASP.NET Core 1.0
本文转自:https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/ One of the new ...
- [译]ASP.NET Core 2.0 系列文章目录
基础篇 [译]ASP.NET Core 2.0 中间件 [译]ASP.NET Core 2.0 带初始参数的中间件 [译]ASP.NET Core 2.0 依赖注入 [译]ASP.NET Core 2 ...
- ASP.NET Core 3.0 自动挡换手动挡:在 Middleware 中执行 Controller Action
最近由于发现奇怪的 System.Data.SqlClient 性能问题(详见之前的博文),被迫提前了向 .NET Core 3.0 的升级工作(3.0 Preview 5 中问题已被修复).郁闷的是 ...
- [译]ASP.NET Core 2.0 中间件
问题 如何创建一个最简单的ASP.NET Core中间件? 答案 使用VS创建一个ASP.NET Core 2.0的空项目,注意Startup.cs中的Configure()方法: public vo ...
- [译]ASP.NET Core 2.0 带初始参数的中间件
问题 如何在ASP.NET Core 2.0向中间件传入初始参数? 答案 在一个空项目中,创建一个POCO(Plain Old CLR Object)来保存中间件所需的参数: public class ...
- [译]ASP.NET Core 2.0 全局配置项
问题 如何在 ASP.NET Core 2.0 应用程序中读取全局配置项? 答案 首先新建一个空项目,并添加两个配置文件: 1. appsettings.json { "Section1&q ...
- [译]ASP.NET Core 2.0 机密配置项
问题 如何在ASP.NET Core 2.0中保存机密配置项(不用将其暴露给源代码管理器)? 答案 创建一个ASP.NET Core 2.0空项目,在项目节点上点击右键,并点击菜单项 - 管理用户机密 ...
- [译]ASP.NET Core 2.0 会话状态
问题 如何在ASP.NET Core 2.0中存储会话状态? 答案 创建一个空项目,修改Startup类的ConfigureServices()方法,添加会话状态服务和它后台的存储服务: public ...
- [译]ASP.NET Core 2.0 本地文件操作
问题 如何在ASP.NET Core 2.0中受限地访问本地目录和文件信息? 答案 新建一个空项目,修改Startup类,添加访问本地文件所需的服务: public void ConfigureSer ...
随机推荐
- CentOS安装MySQL-5.6.10+安全配置
注:以下所有操作均在CentOS 6.5 x86_64位系统下完成. #准备工作# 在安装MySQL之前,请确保已经使用yum安装了各类基础组件,具体见<CentOS安装LNMP环境的基础组件& ...
- 域普通用户执行金蝶K/3权限不够解决方法
一.问题 公司财务部的机器加入域后,用户一直授予本地管理员的权限,主管坚持要撤销管理员权限,而金蝶K3没管理员权限又无法执行. 报错信息为“注册表许可权不够,请参考安装目录的帮助档案进行许可权的配置. ...
- BZOJ 1212: [HNOI2004]L语言 [AC自动机 DP]
1212: [HNOI2004]L语言 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1367 Solved: 598[Submit][Status ...
- JavaMail和James
JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口.它是Sun发布的用来处理email的API.它可以方便地执行一些常用的邮件传输.我们可以基于JavaMail开发出类似于Micr ...
- 细说 Form (表单)
细说 Form (表单) Form(表单)对于每个WEB开发人员来说,应该是再熟悉不过的东西了,可它却是页面与WEB服务器交互过程中最重要的信息来源. 虽然Asp.net WebForms框架为了帮助 ...
- [LeetCode] Third Maximum Number 第三大的数
Given a non-empty array of integers, return the third maximum number in this array. If it does not e ...
- [LeetCode] Remove K Digits 去掉K位数字
Given a non-negative integer num represented as a string, remove k digits from the number so that th ...
- [LeetCode] Counting Bits 计数位
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the ...
- [LeetCode] Remove Element 移除元素
Given an array and a value, remove all instances of that value in place and return the new length. T ...
- 20145215&20145307《信息安全系统设计基础》实验五 网络通信
小组成员:20145215卢肖明.20145307陈俊达 实验报告链接:信息安全系统设计基础--实验五实验报告