ASP.NET Core Middleware

中间件(Middleware)是ASP.NET Core中的一个重要特性。所谓中间件就是嵌入到应用管道中用于处理请求和响应的一段代码。ASP.NET Core Middleware可以分为两种类型:

  • Conventional Middleware

  • IMiddleware

Conventional Middleware

这种中间件没有实现特定的接口或者继承特定类,它更像是Duck Typing (你走起路来像个鸭子, 叫起来像个鸭子, 那么你就是个鸭子)。有两种表现形式:

匿名方法

这种方式又称为内联中间件(in-line middleware),可以使用Run, Map, Use,MapWhen等扩展方法来实现。如:

public class Startup
{public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>{// Do work that doesn't write to the Response.await next.Invoke();// Do logging or other work that doesn't write to the Response.        });
    }
}

IApplicationBuilder的扩展方法:Run、Map、MapWhen及
Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware),最终都会调用IApplicationBuilder接口中的Use(Func<RequestDelegate, RequestDelegate> middleware)方法来实现向请求处理管道中注入中间件,后面会对源码做分析。

自定义中间件类

这种形式利于代码的复用,如:

public class XfhMiddleware
{private readonly RequestDelegate _next;//在应用程序的生命周期中,中间件的构造函数只会被调用一次public XfhMiddleware(RequestDelegate next)
    {this._next = next;
    }public async Task InvokeAsync(HttpContext context)
    {// Do something...await _next(context);
    }
}public static class XfhMiddlewareExtension
{public static IApplicationBuilder UseXfhMiddleware(this IApplicationBuilder builder)
    {// 使用UseMiddleware将自定义中间件添加到请求处理管道中return builder.UseMiddleware<XfhMiddleware>();
    }
}

 

将自定义中间件配置到请求处理管道中

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseXfhMiddleware();
}

IMiddleware

IMiddleware提供了强类型约束的中间件,其默认实现是MiddlewareFactory,接口定义如下:

public interface IMiddleware
{
    Task InvokeAsync(HttpContext context, RequestDelegate next);
}

IMiddlewareFactory用于创建IMiddleware实例及对实例进行回收,接口定义:

public interface IMiddlewareFactory
{public IMiddleware Create (Type middlewareType);    public void Release (IMiddleware middleware);
}

 

自定义IMiddleware类型中间件

public class MyMiddleware : IMiddleware
{public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {await next(context);
    }
}public static class MyMiddlewareExtensions
{public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {return builder.UseMiddleware<MyMiddleware>();
    }
}

 

将中间件注入到请求处理管道:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMyMiddleware();
}

 

使用IMiddleware类型的中间件需要在容器中进行注册,否则抛异常,具体原因下面分析:

 

 

将中间件注入到容器中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<MyMiddleware>();
    services.AddMvc();
}

 

一段警告

下面贴一段微软文档中的警告,大意是不要试图去改变已发往客户端的响应内容,否则可能会引发异常。实在是太懒了,不想翻译就把原文贴出来了:

Warning

Don't call next.Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started throw an exception. For example, changes such as setting headers and a status code throw an exception. Writing to the response body after calling next:

  • May cause a protocol violation. For example, writing more than the stated Content-Length.

  • May corrupt the body format. For example, writing an HTML footer to a CSS file.

HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.


UseMiddleware

前面将自定义中间件注入到请求处理管道时用到了UseMiddleware方法,从方法签名中可以看到UserMiddleware可以接受多个参数:

public static class UseMiddlewareExtensions
{public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app,  params object[] args);   public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, 
            Type middleware, params object[] args);
}

 

接下来我们看下UserMiddleware方法的具体实现,由于该方法代码量较大,所以这里只看其中的关键部分,方法整体流程如下:

public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware,params object[] args)
{// IMiddleware类型if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo()))
    {// IMiddleware doesn't support passing args directly since it's// activated from the containerif (args.Length > 0)
        {throw new NotSupportedException(
                Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware)));
        }return UseMiddlewareInterface(app, middleware);
    }    // Conventional Middlewarevar applicationServices = app.ApplicationServices;return app.Use(next =>{// 判断传入的中间件是否符合约束    });
}

 

  • 该方法首先判断传入的middleware是否是IMiddleware类型,如果是则调用UseMiddlewareInterface

从这段代码中可以看到IMiddlewareFactory负责创建并回收IMiddleware对象

public static class UseMiddlewareExtensions
{private static IApplicationBuilder UseMiddlewareInterface(IApplicationBuilder app, Type middlewareType)
    {return app.Use(next =>{return async context =>{// 从容器中获取IMiddlewareFactory实例var middlewareFactory =(IMiddlewareFactory) context.RequestServices.GetService(typeof(IMiddlewareFactory));if (middlewareFactory == null)
                {// No middleware factorythrow new InvalidOperationException(
                 Resources.FormatException_UseMiddlewareNoMiddlewareFactory(typeof(IMiddlewareFactory)));
                }                var middleware = middlewareFactory.Create(middlewareType);if (middleware == null)
                {// The factory returned null, it's a broken implementationthrow new InvalidOperationException(
                        Resources.FormatException_UseMiddlewareUnableToCreateMiddleware(middlewareFactory.GetType(),
                            middlewareType));
                }                try{await middleware.InvokeAsync(context, next);
                }finally{
                    middlewareFactory.Release(middleware);
                }
            };
        });
    }
}

 

从MiddlewareFactory的Create方法中可以看到,IMiddleware实例是从容器中获取的,若容器中找不到则会抛出异常:

public class MiddlewareFactory : IMiddlewareFactory
{private readonly IServiceProvider _serviceProvider;    public MiddlewareFactory(IServiceProvider serviceProvider)
    {this._serviceProvider = serviceProvider;
    }    public IMiddleware Create(Type middlewareType)
    {return ServiceProviderServiceExtensions.GetRequiredService(this._serviceProvider, middlewareType) as IMiddleware;
    }    public void Release(IMiddleware middleware)
    {
    }
}

 

  • 若是Conventional Middleware则判断传入的middleware是否符合约束

首先判断传入的middleware中是否仅包含一个名称为Invoke或InvokeAsync的公共实例方法

// UseMiddlewareExtensions类中的两个常量internal const string InvokeMethodName = "Invoke";internal const string InvokeAsyncMethodName = "InvokeAsync";// UserMiddleware方法var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public);var invokeMethods = methods.Where(m =>string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal)|| string.Equals(m.Name, InvokeAsyncMethodName, StringComparison.Ordinal)
).ToArray();if (invokeMethods.Length > 1)
{throw new InvalidOperationException(
        Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName, InvokeAsyncMethodName));
}if (invokeMethods.Length == 0)
{throw new InvalidOperationException(
        Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName, InvokeAsyncMethodName,
            middleware));
}

 

其次判断方法的返回类型是否是Task:

var methodInfo = invokeMethods[0];if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType))
{throw new InvalidOperationException(
        Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName,
            InvokeAsyncMethodName, nameof(Task)));
}

 

然后再判断,方法的第一个参数是否是HttpContext类型:

var parameters = methodInfo.GetParameters();if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext))
{throw new InvalidOperationException(
        Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName, InvokeAsyncMethodName,
            nameof(HttpContext)));
}

 

对于Invoke或InvokeAsync仅包含一个HttpContext类型参数的情况用到了反射(ActivatorUtilities.CreateInstance方法中)来构建RequestDelegate

var ctorArgs = new object[args.Length + 1];
ctorArgs[0] = next;
Array.Copy(args, 0, ctorArgs, 1, args.Length);var instance = ActivatorUtilities.CreateInstance(app.ApplicationServices, middlewaif (parameters.Length == 1)
{return (RequestDelegate) methodInfo.CreateDelegate(typeof(RequestDelegate), in}

 

对于包含多个参数的情况,则使用了表达式树来构建RequestDelegate

var factory = Compile<object>(methodInfo, parameters);return context =>{var serviceProvider = context.RequestServices ?? applicationServices;if (serviceProvider == null)
    {throw new InvalidOperationException(
            Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(
                nameof(IServiceProvider)));
    }return factory(instance, context, serviceProvider);
};

 

完整的代码可以在Github上看到。

Use(Func<RequestDelegate, RequestDelegate> middleware)

上述所有中间件,最终都会调用IApplicationBuilder接口中的Use(Func<RequestDelegate, RequestDelegate> middleware)方法来实现向请求处理管道中注册中间件,该方法在ApplicationBuilder类的实现如下:

public class ApplicationBuilder : IApplicationBuilder
{private readonly IList<Func<RequestDelegate, RequestDelegate>> _components =new List<Func<RequestDelegate, RequestDelegate>>();public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
    {this._components.Add(middleware);return this;
    }
}

 

从上面代码中可以看到,中间件是一个RequestDelegate类型的委托,请求处理管道其实是一个委托列表,请求委托签名如下:

public delegate Task RequestDelegate(HttpContext context);

 


与ASP.NET处理管道的区别

 

 

 

传统的ASP.NET的处理管道是基于事件模型的,处理管道有多个IHttpModule和一个IHttpHandler组成。请求处理管道中各个模块被调用的顺序取决于两方面:

  • 模块所注册事件被触发的先后顺序
  • 注册同一事件的不同模块执行先后顺序有Web.config中的配置顺序决定

 

 

 

ASP.NET Core的请求处理管道则是有一堆中间件组成,相对ASP.NET更简单。

中间件处理请求和响应的顺序只与其在代码中的注册顺序有关:处理请求按注册顺序依次执行,处理响应按注册顺序反方向依次执行。

其次,在ASP.NET Core中只需使用代码,而无需使用Global.asax和Web.config来配置请求处理管道。

小结

所谓中间件就是嵌入到应用管道中用于处理请求和响应的一段代码,它主要有两个作用:

  • 处理请求和响应
  • 可以阻止请求发往请求处理管道中的下一个中间件

在ASP.NET Core中,中间件是以RequestDelegate委托的形式体现的。

ASP.NET Core中整个请求处理管道的创建是围绕这种IApplicationBuilder接口进行的,请求处理管道是一个List<RequestDelegate>类型的列表。


原文地址:https://blog.51cto.com/u_7605937/2704760

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


数组的定义 Dim MyArray MyArray = Array(1‚5‚123‚12‚98) 可扩展数组 Dim MyArray() for i = 0 to 10
\'参数: \'code:要检测的代码 \'leixing:html或者ubb \'nopic:代码没有图片时默认值
演示效果: 代码下载: 点击下载
环境:winxp sp2 ,mysql5.0.18,mysql odbc 3.51 driver 表采用 myisam引擎。access 2003  不同的地方: 
其实说起AJAX的初级应用是非常简单的,通俗的说就是客户端(javascript)与服务端(asp或php等)脚本语言的数据交互。
<% ’判断文件名是否合法 Function isFilename(aFilename)  Dim sErrorStr,iNameLength,i  isFilename=TRUE
在调用的时候加入判断就行了. {aspcms:navlist type=0 } {if:[navlist:i]<6} < li><a href=\"[navlist:link]\" target=\"_top\">[navlist:name]</a> </li>
导航栏调用 {aspcms:navlist type=0}     <a href=\"[navlist:link]\">[navlist:name]</a>
1.引入外部文件: {aspcms:template src=infobar.html} 2.二级下拉菜单 <ul class=\"nav\">
downpic.asp页面:  <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
Cookies是数据包,可以让网页具有记忆功能,在某台电脑上记忆一定的信息。Cookies的工作原理是,第一次由服务器端写入到客户端的系统中。以后每次访问这个网页,都是先由客户端将Cookies发送到服务器端,再由服务器端
很简单,在需要调用的地方用这种模式 {aspcms:content sort={aspcms:sortid} num=17 order=isrecommend}
网站系统使用ACCESS数据库时,查询时怎么比较日期和时间呢?为什么常常比较出来却是错误的呢?比如早的日期比迟的日期大?
str1=\"1235,12,23,34,123,21,56,74,1232\" str2=\"12\" 问题:如何判断str2是否存在str1中,要求准确找出12,不能找出str1中的1235、123、1232
实例为最新版本的kindeditor 4.1.5. 主要程序: <% Const sFileExt=\"jpg|gif|bmp|png\" Function ReplaceRemoteUrl(sHTML,sSaveFilePath,sFileExt)
用ASP实现搜索引擎的功能是一件很方便的事,可是,如何实现类似3721的智能搜索呢?比如,当在搜索条件框内输入“中国人民”时,自动从中提取“中国”、“人民”等关键字并在数据库内进行搜索。看完本文后,你就可以发
首先感谢ASPCMS官网注册用户xing0203的辛苦付出!一下为久忆YK网络转载原创作者xing0203的文章内容!为了让小白更加清楚的体验替换过程,久忆YK对原文稍作了修改!
数据库连接: <% set conn=server.createobject(\"adodb.connection\") conn.open \"driver={microsoft access driver (*.mdb)};dbq=\"&server.mappath(\"数据库名\")
第1步:修改plugins下的image/image.js 找到\'<input type=\"button\" class=\"ke-upload-button\" value=\"\' + lang.upload + \'\" />\',
asp函数: <% Const sFileExt=\"jpg|gif|bmp|png\" Function ReplaceRemoteUrl(sHTML,sSaveFilePath,sFileExt)