ASP.NET 外文翻译 - 从底层了解ASP.NET的结构

jasonms0 贡献于2013-06-27

作者 dbc  创建于2012-04-05 09:02:00   修改者dbc  修改于2012-04-05 09:03:00字数16245

文档摘要:  ASP.NET是一个用于构建Web程序的强大平台,提供了强大的柔性和能力以至于它可以构建任意的Web程序。许多人仅仅对处于ASP.NET高层次的框架如:WebForms和WebServices比较熟悉,因此,在这篇文章里,我将会阐述有关ASP.NET比较底层的知识,并且将会解释,如何将请求从Web Server移交给ASP.NET运行时,然后通过ASP.NET HTTP管道处理这些请求。
关键词:

原文1 A low-level Look at the ASP.NET Architecture Abstract ASP.NET is a powerful platform for building Web applications that provides a tremendous amount of flexibility and power for building just about any kind of Web application. Most people are familiar only with the high level frameworks like WebForms and WebServices which sit at the very top level of the ASP.NET hierarchy. In this article I’ll describe the lower level aspects of ASP.NET and explain how requests move from Web Server to the ASP.NET runtime and then through the ASP.NET Http Pipeline to process requests. What is ASP.NET Let’s start with a simple definition: What is ASP.NET? I like to define ASP.NET as follows: ASP.NET is a sophisticated engine using Managed Code for front to back processing of Web Requests.It's much more than just WebForms and Web Services… ASP.NET is a request processing engine. It takes an incoming request and passes it through its internal pipeline to an end point where you as a developer can attach code to process that request. This engine is actually completely separated from HTTP or the Web Server. In fact, the HTTP Runtime is a component that you can host in your own applications outside of IIS or any server side application altogether. The runtime provides a complex yet very elegant mechanism for routing requests through this pipeline. There are a number of interrelated objects, most of which are extensible either via subclassing or through event interfaces at almost every level of the process, so the framework is highly extensible. Through this mechanism it’s possible to hook into very low level interfaces such as the caching, authentication and authorization. You can even filter content by pre or post processing requests or simply route incoming requests that match a specific signature directly to your code or another URL. There are a lot of different ways to accomplish the same thing, but all of the approaches are straightforward to implement, yet provide flexibility in finding the best match for performance and ease of development. The entire ASP.NET engine was completely built in managed code and all of the extensibility functionality is provided via managed code extensions. This is a testament to the power of the .NET framework in its ability to build sophisticated and very performance oriented architectures. Above all though, the most impressive part of ASP.NET is the thoughtful design that makes the architecture easy to work with, yet provides hooks into just about any part of the request processing. With ASP.NET you can perform tasks that previously were the domain of ISAPI extensions and filters on IIS – with some limitations, but it’s a lot closer than say ASP was. ISAPI is a low level Win32 style API that had a very meager interface and was very difficult to work for sophisticated applications. Since ISAPI is very low level it also is very fast, but fairly unmanageable for application level development. So, ISAPI has been mainly relegated for some time to providing bridge interfaces to other application or platforms. But ISAPI isn’t dead by any means. In fact, ASP.NET on Microsoft platforms interfaces with IIS through an ISAPI extension that hosts .NET and through it the ASP.NET runtime. ISAPI provides the core interface from the Web Server and ASP.NET uses the unmanaged ISAPI code to retrieve input and send output back to the client. The content that ISAPI provides is available via common objects like HttpRequest and HttpResponse that expose the unmanaged data as managed objects with a nice and accessible interface. The ISAPI Connection ISAPI is a low level unmanged Win32 API. The interfaces defined by the ISAPI spec are very simplistic and optimized for performance. They are very low level – dealing with raw pointers and function pointer tables for callbacks - but they provide he lowest and most performance oriented interface that developers and tool vendors can use to hook into IIS. Because ISAPI is very low level it’s not well suited for building application level code, and ISAPI tends to be used primarily as a bridge interface to provide Application Server type functionality to higher level tools. For example, ASP and ASP.NET both are layered on top of ISAPI as is Cold Fusion, most Perl, PHP and JSP implementations running on IIS as well as many third party solutions such as my own Web Connection framework for Visual FoxPro. ISAPI is an excellent tool to provide the high performance plumbing interface to higher level applications, which can then abstract the information that ISAPI provides. In ASP and ASP.NET, the engines abstract the information provided by the ISAPI interface in the form of objects like Request and Response that read their content out of the ISAPI request information. Think of ISAPI as the plumbing. For ASP.NET the ISAPI dll is very lean and acts merely as a routing mechanism to pipe the inbound request into the ASP.NET runtime. All the heavy lifting and processing, and even the request thread management happens inside of the ASP.NET engine and your code. As a protocol ISAPI supports both ISAPI extensions and ISAPI Filters. Extensions are a request handling interface and provide the logic to handle input and output with the Web Server – it’s essentially a transaction interface. ASP and ASP.NET are implemented as ISAPI extensions. ISAPI filters are hook interfaces that allow the ability to look at EVERY request that comes into IIS and to modify the content or change the behavior of functionalities like Authentication. Incidentally ASP.NET maps ISAPI-like functionality via two concepts: Http Handlers (extensions) and Http Modules (filters). We’ll look at these later in more detail. ISAPI is the initial code point that marks the beginning of an ASP.NET request. ASP.NET maps various extensions to its ISAPI extension which lives in the .NET Framework directory: 本文摘自http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp 译文1 从底层了解ASP.NET的结构 · 摘要 ASP.NET是一个用于构建Web程序的强大平台,提供了强大的柔性和能力以至于它可以构建任意的Web程序。许多人仅仅对处于ASP.NET高层次的框架如:WebForms和WebServices比较熟悉,因此,在这篇文章里,我将会阐述有关ASP.NET比较底层的知识,并且将会解释,如何将请求从Web Server移交给ASP.NET运行时,然后通过ASP.NET HTTP管道处理这些请求。 1 ASP.NET是什么? 我们从最简单的定义开始,ASP.NET是什么?我通常喜欢用如下语句来描述ASP.NET。 ASP.NET是完全使用托管代码处理Web请求的一个成熟引擎平台。它不仅仅只是WebForms和WebServices。  ASP.NET是一个请求处理引擎。它获取客户端请求,然后通过它内置的管道,把请求传到一个终点,在这个终点,开发者可以添加处理这个请求的逻辑代码。实际上这个引擎和HTTP或者Web Server是完全分开的。事实上,HTTP运行时是一个组件,你可以把它宿主在IIS之外的应用程序上。甚至完全可以和其它的服务组合在一起。通过使用内置的管道路由请求,HTTP运行时提供了一套复杂的,但却很优雅的机制。在处理请求的每一个层面都牵涉到许多对象,但大多数对象都可以通过派生或者事件接口来扩展。所以,此框架具有非常高的可扩展性。通过这一套机制,可以进入较低层次的接口如:缓存,身份验证,授权等是有可能的。你可以在处理请求之前或之后过滤内容,或者仅仅把匹配指定签名的客户端请求直接路由到你的代码里或转向其它的URL。针对同一件事情,可以通过不同的处理方法完成,而且实现代码都非常的直观。除此之外,在容易开发和性能之间,HTTP运行时还提供了最佳的灵活性。  整个ASP.NET引擎完全构建在托管代码里,所有的扩展性功能都是通过托管代码的扩展提供。对于功能强大的.NET框架而言,使用自己的东西,构建一个成熟的、高性能的引擎体系结构已经成为一个遗嘱。尽管如此,但重要的是,ASP.NET给人印象最深的是高瞻远瞩的设计,这使得在其之上的工作变得非常容易,并且提供了几乎可以钩住请求处理当中任意部分的能力。   使用ASP.NET可以完成一些任务,之前这些任务是使用IIS上的ISAPI扩展和过滤来完成的。尽管还有一些限制,但与ASP相比,已经有了很大的进步。ISAPI是底层Win32样式的API,仅它的接口就有1兆,这对于大型的程序开发是非常困难的。由于ISAPI是底层的接口,因此它的速度也是非常的快。但对于企业级的程序开发是相当的难于管理的。所以,在一定的时间内,ISAPI主要充当其它应用程序或平台的桥接口。但是无论如何,ISAPI没有被废弃。事实上,微软平台上的ASP.NET和IIS的接口是通过宿主在.NET里的ISAPI扩展来通信的,然后直达ASP.NET运行时。ISAPI提供了与Web Server通信的核心接口,然后ASP.NET使用非托管代码获取请求以及对客户端请求发出响应。ISAPI提供的内容经由公共对象类似于HttpRequest和HttpResponse,通过一个设计优良的、可访问的接口,以托管对象的方式暴露非托管数据。 2 从浏览器到ASP.NET 让我们从一个典型的ASP.NET Web请求的生命周期的起点开始。用户通过在浏览器中键入一个URL,点击一个超链接,提交一个HTML表单(一个post请求),或者一个客户端程序调用基于ASP.NET的WebService(通过ASP.NET提供服务)。在服务器端,IIS5或者IIS6将会收到这个请求。ASP.NET的底层通过ISAPI扩展与IIS通信,然后,通过ASP.NET,这个请求通常被路由到一个带有.aspx扩展名的页面。但是,这个处理过程如何工作,则完全依赖于HTTP处理器(handler)的执行。这个处理器将被安装用于处理指定的扩展。在IIS中,.aspx经由“应用程序扩展”被映射到ASP.NET ISAPI的dll文件:aspnet_isapi.dll。每一个触发ASP.NET的请求,都必须经由一个已经注册的,并且指向aspnet_isapi.dll的扩展名来标识。 注:ISAPI是自定义Web请求处理中第一个并且具有最高性能的IIS入口点。 依靠扩展名,ASP.NET把一个请求路由到一个恰当的处理器,该处理器则负责处理这个请求。举个例子,WebServices的扩展名.asmx不会把一个请求路由到磁盘上的某一个页面,而是会路由到在定义中附加了指定特性(WebMethodAttribute)的类,此特性会把它标识成一个Web Services的实现。许多其它的处理器将随着ASP.NET一起被安装。当然也可以定义你自己的处理器。在IIS里所有的HttpHandler被映射并指向ASP.NET ISAPI扩展,并且这些HttpHandler也都在web.config里配置,用于把请求路由到指定的HTTP处理器里执行。每一个处理器都是一个.NET类,用于处理指定的扩展。而这些处理器可以处理简单到只有几行代码的Hello World,也可以处理复杂到类似ASP.NET的页面以及执行WebService。就目前而言,仅仅需要理解扩展就是一种基本的映射机制,ASP.NET用它可以从ISAPI里获取一个请求,然后把请求路由到指定处理该请求的处理器中。 原文2 Thirteen ASP.NET MVC extensibility points you have to know Abstract One of the main design principles ASP.NET MVC has been designed with is extensibility. Everything (or most of) in the processing pipeline is replaceable so, if you don’t like the conventions (or lack of them) that ASP.NET MVC uses, you can create your own services to support your conventions and inject them into the main pipeline. In this post I’m going to show 13 extensibility points that every ASP.NET MVC developer should know, starting from the beginning of the pipeline and going forward till the rendering of the view. 1. RouteConstraint Usually you could put some constrains on url parameters using regular expressions, but if your constrains depend on something that is not only about the single parameter, you can implement the IRouteConstrains’s method and put your validation logic in it. One example of this is the validation of a date: imagine an url that has year, month and date on different url tokens, and you want to be able to validate that the three parts make a valid date. ·2. RouteHandler Not really specific to ASP.NET MVC, the RouteHandler is the component that decide what to do after the route has been selected. Obviously if you change the RouteHandler you end up handling the request without ASP.NET MVC, but this can be useful if you want to handle a route directly with some specific HttpHanlders or even with a classic WebForm. 3. ControllerFactory The controller factory is the component that, based on the route, chooses which controller to instantiate and instantiate it. The default factory looks for anything that implements IController and whose name ends with Controller, and than create an instance of it through reflection, using the parameter-less constructor. But if you want to use Dependency Injection you cannot use it, and you have to use a IoC aware controller factory: there are already controller factory for most of the IoC containers. You can find them in MvcContrib or having a look at the Ninject Controller Factory. 4. ActionInvoker ActionInvoker is responsible for invoking the action based on it’s name. The default action invoker looks for the action based on the method name, the action name and possibly other selector attributes. Then it invokes the action method together with any filter defined  and finally it executes the action result. If you read carefully you probably understood that most of the execution pipeline is inside the logic of the default ControllerActionInvoker class. So if you want to change any of these conventions, from the action method’s selection logic, to the way http parameters are mapped to action parameters, to the way filters are chosen and executed, you have to extend that class and override the method you want to change. A good example of this, is the NinjectActionInvoker I developed to allow injection of dependencies inside filters. 5. ActionMethodSelectorAttribute Actions, with the default action invoker, are selected based on their name, but you can finer tune the selection of actions implementing your own Method Selector. The framework already comes with the AcceptVerbs attribute that allows you to specify to which HTTP Verb an action has to respond to. A possible scenario for a custom selector attribute is if you want to choose one action or another based on languages supported by the browser or based on the type of browser, for example whether it is a mobile browser or a desktop browser. 6. AuthorizationFilter These kind of filters are executed before the action is executed, and their role is to make sure the request is “valid”. There are already a few Authorization filters inside the framework, the most “famous” of which is the Authorize attribute that checks whether the current user is allowed to execute the action. Another is the the ValidateAntiForgeryToken that prevents CSRF attacks. If you want to implement your own authorization schema, the interface you have to implement is IAuthorizationFilter. An example could be the hour of the day. 7. ActionFilter Action Filters are executed before and after an action is executed. One of the core filters is the OutputCache filter, but you can find many other usages for this filter. This is the most likely extension point you are going to use, as, IMHO, it’s critical to a good componentization of views: the controller only has to do its main stuff, and all the other data needed by the view must be retrieved from inside action filters. 8. ModelBinder The default model binder maps HTTP parameters to action method parameters using their names: a http parameter named user.address.city will be mapped to the City property of the Address object that itself is a property of the method parameter named user. The DefaultModelBinder works also with arrays, and other list types. But it can be pushed even further: for example you might use it to convert the id of the person directly to the Person object looking up on the database. This approach is explained better in the following post Timothy Khouri (aka SingingEels): Model Binders in ASP.NET MVC. The code is based on the preview 5, but the concept remains the same. ·9. ControllerBase All controllers inherit from the base class Controller. A good way to encapsulate logic or conventions inside your actions is to create you own layer supertype and have all your controllers to inherit from it. ·10. ResultFilter Like the ActionFiters, the ResultFilters are execute before and after the ActionResult is executed. Again, the OutputCache filter is an example of a ResultFilter. The usual example that is done to explain this filter is logging. If you want to log that a page has been returned to the user, you can write a custom RenderFilter that logs after the ActionResult has been executed. ·11. ActionResult ASP.NET MVC comes with many different kind of results to render views, to render JSON, plain text, files and to redirect to other actions. But if you need some different kind of result you can write your own ActionResult and implement the ExecuteResult method. For example, if you want to send a PDF file as result you could write your own ActionResult that use a PDF library to generate the PDF. Another possible scenario is the RSS feed: read more about how to write a RssResult in this post. Look at implementing a custom action result when the only peculiarity is how the result is returned to the user. ·12. ViewEngine Probably you are not going to write your own view engine, but there are a few that you might consider using instead of the default WebForm view engine. The most interesting one, IMHO, is Spark. But if you really want to write your own view engine, have a look at this post by Brad Wilson: Partial Rendering & View Engines in ASP.NET MVC. ·13. HtmlHelper Views must be very dumb and thin, and they should only have html markup and calls to HtmlHelpers. There should be no code inside the views, so helpers come very handy for extracting the code from the view and putting it into something that is testable. As Rob Conery says: “If there's an IF, make a Helper”. What is an HtmlHelper? Basically it’s just an extension method of the HtmlHelper class, but that’s the only requirement. 本文摘自http://codeclimber.net.nz/ 译文2 ASP.NET MVC中你必须知道的13个扩展点 摘要 ASP.NET MVC设计的主要原则之一是可扩展性。处理管线(processing pipeline)上的所有(或大多数)东西都是可替换的。因此,如果您不喜欢ASP.NET MVC所使用的约定(或缺乏某些约定),您可以创建自己的服务来支持您的约定,并将其注入到主管线中。 在本文中,我们将从管线开始直到视图呈现,逐一向您展示每个ASP.NET MVC开发者都必须了解13个扩展点。 1.RouteConstraint 通常情况下你可以使用正则表达式对url参数进行约束,但如果您的约束不仅仅取决于单一参数,您可以实现IRouteConstrains的方法,并在其中添加你的验证逻辑。 比如对日期的验证,url中可能会包含年、月、日,而你需要验证这三者是否可以组合成一个有效的日期。 2.RouteHandler RouteHandler是在路由选择之后进行处理的组件,它并不仅仅针对ASP.NET MVC。显然,如果您改变了RouteHandler,那么对请求的处理将不再使用ASP.NET MVC,但这在您使用其他HttpHandler或经典的WebForm进行路由处理时却是非常有用的。 3.ControllerFactory ControllerFactory是基于路由的组件,它选择正确的controller并对其实例化。default factory会查找实现了IController并且以Controller结尾的类,然后通过反射使用无参构造函数进行实例化。 但如果您希望使用依赖注入,就不能再使用default factory,而必须使用支持IoC的controller factory。MvcContrib和Ninject Controller Factory都包含支持IoC容器的controller factory。 4.ActionInvoker ActionInvoker顾名思义是负责调用(invoke)action的。默认的action invoker通过方法名、action名或其他可能的selector attribute来查找action,然后调用action方法以及定义的filter,最终执行得到action result。 你会发现大部分执行管线存在于ControllerActionInvoker类的逻辑之中。因此,如果希望改变这些约定,如action方法的选择逻辑、http参数映射到action参数的方式、选择和执行filter的方式等,您需要扩展该类并重写需要修改的方法。 可以参阅NinjectActionInvoker I developed to allow injection of dependencies inside filters。 5.ActionMethodSelectorAttribute 使用默认的action invoker时,action的选择是基于名称的。您也可以实现自己的Method Selector以改善对于action的选择。在框架中已经包含了AcceptVerbs特性,它允许您指定使用哪一个HTTP Verb来处理action的响应。 例如,您也许会希望基于浏览器所支持的语言或浏览器类型(如移动设备的浏览器或桌面浏览器)来进行action的选取。 6.AuthorizationFilter 这种过滤器是在action执行之前执行的,用来确保请求是有效的。 框架中已经包含了一些autorization过滤器,最有名的莫过于Authorize特性,它用来检查当前用户是否允许执行该action。另一个是用来阻止CSRF攻击的ValidateAntiForgeryToken。如果您希望实现自己的authorization,那么必须实现接口。例如,日期中的小时。 7.ActionFilter Action Filters在action执行前后执行。OutputCache过滤器是几个核心过滤器之一。这可能是您最有可能使用的扩展点,并且在我看来,controller只关心它的主要工作,而view所需要的所有其他数据都必须从action过滤器内部获取,这样的实现对于一个组织良好的view来说,是十分关键的。 8.ModelBinder 默认的model binder使用参数名称进行HTTP参数到action方法参数的映射。例如,http参数user.address.city将映射到方法参数user的Address属性的City属性。DefaultModelBinder也同样适用于数组和其他列表类型。 更进一步来说,例如,您可能希望从数据库中进行检索,直接根据person的id将其转换为Person对象。Timothy Khouri(网名SingingEels)在他的文章Model Binders in ASP.NET MVC中更好的阐述了这种方法。他的代码基于Preview 5,但其理念是一样的。 9.ControllerBase 所有的Controller均继承自基类Controller。要想在action中封装自己的逻辑和约定,创建自己的父类使所有Controller继承自该类,是一种很好的方式。 10.ResultFilter 与ActionFilter类似,ResultFilters在ActionResult前后执行。OutputCache过滤器也可以作为ResultFilter的示例。另外,比较常用的诠释这种过滤器的示例是日志记录。如果您希望在页面返回给用户时记录日志,可以编写自定义的RenderFilter,在ActionResult执行之后记录日志。 11.ActionResult ASP.NET MVC提供了很多result用来呈现视图、JSON、纯文本、文件并重定向到其他action。如果您需要其他类型的result,可以自定义ActionResult,并实现ExecuteResult方法。例如,如果您希望将PDF文件作为结果发送,您需要使用PDF库编写能够生成PDF的ActionResult。又如RSS feed,可参见how to write a RssResult in this post。 12.ViewEngine 您可能不需要编写自己的view engine,但您也许可以考虑使用其他引擎来替代默认的WebForm view engine。在我看来,最有趣的引擎就是Spark。 如果您确实希望编写自己的view engine,可以看一下Brad Wilson的文章: Partial Rendering & View Engines in ASP.NET MVC。 13.HtmlHelper 视图必须十分简单整洁,它们只能包含html标记并调用HtmlHelper的辅助方法。视图中不能包含任何代码,所以辅助方法必须十分方便,使您可以将代码从视图中提取出来,放到一个可测试的环境中去。正如Rob Conery所说:如果有if,就构造辅助方法(If there's an IF, make a Helper)。 什么是HtmlHelper辅助方法?其实就是HtmlHelper类的扩展方法,这是唯一的要求。 你可以从Rob的文章Avoiding Tag Soup中了解到为什么说HtmlHelper是封装视图中代码的好方法

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 6 金币 [ 分享文档获得金币 ] 1 人已下载

下载文档