Examining Application Startup in ASP.NET 5

By Steve Smith  June 23, 2015

ASP.NET 5 differs from previous versions of ASP.NET in many ways. Gone is the default ASP.NET event life cycle, and along with it, the global.asax file (which itself was an evolved version of global.asa from the ASP days). Also gone is the XML-based web.config file, in most cases, though you may still find it making appearances in your wwwroot folder in some cases.

Note: The official ASP.NET 5 documentation is still under development. It’s being developed using GitHub and open source, and Falafel Software is one of the official contributors. Some of the links in this article are still under construction, but you should see them fill out by the time ASP.NET 5 is officially released. A good place to get started with this topic is the Application Startup article that was just published.

ASP.NET 5’s startup system is heavily influenced by prior work in the OWIN space, including project katana. In this new paradigm, the web host environment (not necessarily IIS) will search the application for a starting point, and typically this will be a class called Startup located in the root of the application. At a minimum, this class needs to have a method called Configure(), which the hosting environment will call to configure the application’s request pipeline. If you’re familiar with ASP.NET’s HTTP handlers and modules, you can think of the request delegates that are specified within theConfigure() method as being similar to a combination of these two concepts. Collectively, such request delegates are referred to as middleware.

Having complete and granular access to the HTTP request delegate pipeline allows applications to be constructed with just the features and components they require, and nothing more. It’s extremely lean, composable, and more secure and higher performance by default because only those features that are required are included. This reduces the overall application surface area exposed to attackers, and reduces the work that must be done on each request to the bare minimum.

The request delegate pipeline is constructed as a series of delegates, which can be written simply as lambda expressions or encapsulated within their own classes. Each delegate can perform some work, call the next delegate, and then do some more work once that call completes. Thus, it’s possible to wrap later delegates within earlier ones, which is important for scenarios like authentication and error handling. At any given point within the pipeline, a delegate can choose not to call the next delegate, even if one is defined, allowing the pipeline to be short-circuited. Thus, the order in which delegates are wired up in the pipeline is very important.

Consider this sample method from the default web site template (in VS2015 RC):

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
{
    if (env.IsEnvironment("Development"))
    {
        app.UseBrowserLink();
        app.UseErrorPage(ErrorPageOptions.ShowAll);
        app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
    }
    else
    {
        // Add Error handling middleware which catches all application specific errors and
        // sends the request to the following path or controller action.
        app.UseErrorHandler("/Home/Error");
    }

    // Add static files to the request pipeline.
    app.UseStaticFiles();

    // Add cookie-based authentication to the request pipeline.
    app.UseIdentity();

    // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
    // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
    // app.UseFacebookAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "Home", action = "Index" });
    });
}

In this example, the pipeline is configured slightly differently in a development environment vs. in production. In development, the application wires up BrowserLink (for use with Visual Studio) as well as helpful error pages that should not be deployed to production. In production, a simple error handler page is configured. Next, the application is configured to support static files, and then to use ASP.NET Identity for authentication. Note that since authentication is configured after static files, it will not protect static files (nor will static files incur overhead from checking authentication). Finally, ASP.NET MVC is configured, along with a default route. In each case, a simple UseWhatever() method is used to wire up the pipeline methods, but under the covers these methods are adding request delegates to the application’s pipeline. Although the Configure() method is called when the application starts up, the request delegates that are wired up here are not – they are called on every individual HTTP request that is made to the application.

In addition to Configure, you can optionally specify a method called ConfigureServices, which will configure the default services container (IoC container) for ASP.NET. This allows for dependency injection, which helps ensure your application remains loosely coupled from its underlying implementation. Your controllers, services, and other application classes should try to follow the SOLID principles, as well as the Explicit Dependencies Principle, which will help to ensure you don’t end up with a brittle, tightly coupled implementation. These principles have been followed by ASP.NET itself in this version. Note that your Startup class doesn’t depend on any particular base class, nor does it refer to any particular implementation of a web server. Even the parameters it can have injected into it are all interfaces, not concrete types, allowing multiple web servers to be supported, even across multiple platforms.

You can see how ASP.NET 5’s hosting implementation loads an individual application by examining the Microsoft.AspNet.Hosting package – it’s open source on GitHub. Specifically, you can see how an application is created and its services registered by examining the HostingEngine class, which the Configure class inside its BuildApplication method. The application’s Startup class has its methods mapped to a StartupMethods class by StartupLoader, which allows HostingEngine to call these methods without having any knowledge of your application’s actual Startup class’s type.

Take a look at how these two classes, StartupLoader and HostingEngine, work to start and configure your application. This is fundamental to understanding how ASP.NET 5 applications work at the most basic level. With ASP.NET 5 being developed completely as open source on GitHub, we have much greater ability to examine and understand the underlying design decisions and plumbing that underpins the applications we build on this foundation. Use this to your advantage and make sure you can follow what the two classes above are doing when your application is launched. Do not expect that your understanding of ASP.NET from prior versions will serve you well – this version is a huge change from ASP.NET v1-v4. It’s not quite as big a change as from classic ASP to ASP+/ASP.NET, but it’s close.

时间: 2024-10-15 00:31:54

Examining Application Startup in ASP.NET 5的相关文章

ASP.NET 5 入门——Application Startup

ASP.NET 5 入门--Application Startup? Startup 类? 在 ASP.NET 5 中,Startup 类是一个应用的入口点,我们可以为不同环境配置不同的内容. 编译器会查找项目文件夹下的所有 *.cs 文件进行编译,而运行时会寻找所有命名空间下类名为 Startup 的类作为启动方式. 注解 可以通过设置 project.json 文件选择需要(或不需要)编译的文件和文件夹:也可以设置在不同的程序集中搜索 Startup 类. Startup 类必须定义一个 C

Capturing ASP.NET Application Startup Exceptions

It has become common practice to perform tasks during an ASP.NET applications start up process. These tasks may include registering routes, configuring filters, wiring up third party dependencies, and so much more. Here is the default ASP.NET MVC app

[转]Session and application state in ASP.NET Core

本文转自:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state By Rick Anderson and Steve Smith+ HTTP is a stateless protocol; the Web server treats each HTTP request as an independent request. The server retains no knowledge of variable va

asp.net asp.net application 升级到 asp.net web 解决找不到控件 批量生成.designer文件

颇费周折后,其实很简单,只需要生成designer文件后,重新保存所有页面即可.就是懒得写.懒真的是一种病,手上不能懒,脑子里更不能懒,否则就是给自己挖坑,仔细认真,注意细节!!!! PS:注意修改path变量为自己需要生成的web项目路径 需要注意的是,CodeBehind的路径是绝对路径 参考链接https://oomake.com/question/4935 对于VS2015 ...这里有一个用于从WebSite项目切换到适用于我的Web应用程序项目的VB示例.没有其他解决方案为我工作,这

带你认识ASP Application 对象

ASP Application 对象 Previous Page Next Page 在一起协同工作以完成某项任务的一组 ASP 文件称作应用程序 (application).ASP 中的 Application 对象用于将这些文件捆绑在一起. Application 对象 web 上的一个应用程序可以是一组 ASP 文件.这些 ASP 文件一起协同工作来完成某项任 务.ASP 中的 Application 对象用来把这些文件捆绑在一起. Application 对象用于存储和访问来自任何页面的

ASP.NET中application对象的用法(面试题)

ASP.NET中application对象的用法 本文导读:Application对象是HttpApplicationState类的一个实例,Application状态是整个应用程序全局的.Application对象在服务器内存中存储数量较少又独立于用户请求的数据.由于它的访问速度非常快而且只要应用程序不停止,数据一直存在,我们通常在Application_Start的时候去初始化一些数据,在以后的访问中可以迅速访问和检索. 一.Application对象的理解 Application对象在实际

ASP.NET页面之间传递值(5):Application

Application对象的作用范围是整个全局,也就是说对所有用户都有效.它在整个应用程序生命周期中都是有效的,类似于使用全局变量一样,所 以可以在不同页面中对它进行存取.它和Session变量的区别在于,前者是所有的用户共用的全局变量,后者是各个用户独有的全局变量. 可能有人会问,既然所有用户都可以使用application变量,那他可以用在什么场合呢?这里举个例子:网站访问数.多个请求访问时都可以对它进行操作. 优点:1.使用简单,消耗较少的服务器资源. 2.不仅能传递简单数据,还能传递对象

asp.net core 系列 2 启动Startup类介绍

一.Startup类 ASP.NET Core 应用是一个控制台应用,它在其 Program.Main 方法中创建 Web 服务器.其中Main方法是应用的托管入口点,Main 方法调用 WebHost.CreateDefaultBuilder来创建 Web 主机,自动分配了 Kestrel Web 服务器.IWebHostBuilder 的 Build 方法生成 IWebHost对象调用Run 方法启动WebHost,此时托管应用并开始侦听 HTTP 请求.代码如下所示: 1 public c

ASP.NET Core 3.1 中的Startup类

Startup 类配置服务和应用的请求管道. Startup 类 ASP.NET Core 应用使用 Startup 类,按照约定命名为 Startup. Startup 类: 可选择性地包括 ConfigureServices 方法以配置应用的服务 . 服务是一个提供应用功能的可重用组件. 在 ConfigureServices 中注册服务,并通过依赖关系注入 (DI) 或 ApplicationServices 在整个应用中使用服务 . 包括 Configure 方法以创建应用的请求处理管道