简体   繁体   English

如果我使用的是 OWIN Startup.cs 类并将所有配置移到那里,我是否需要 Global.asax.cs 文件?

[英]Do I need a Global.asax.cs file at all if I'm using an OWIN Startup.cs class and move all configuration there?

Let's say for example in a brand new ASP.NET MVC 5 application made from the MVC with Individual Accounts template, if I delete the Global.asax.cs class and move it's configuration code to Startup.cs Configuration() method as follow, what are the downsides?例如,在一个由 MVC with Individual Accounts 模板制作的全新 ASP.NET MVC 5 应用程序中,如果我删除Global.asax.cs类并将其配置代码移动到Startup.cs Configuration()方法如下,会发生什么缺点是什么?

public partial class Startup
{
     public void Configuration(IAppBuilder app)
     {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ConfigureAuth(app);
    }
}

The upsides for me is that when upgrading ASP.NET 4 applications to ASP.NET 5 and using pieces that now must be configured in the Startup.cs class, I'm not doing dependency injection and other configuration in two different classes that seem related to starting up, and configuration.对我来说的好处是,当将 ASP.NET 4 应用程序升级到 ASP.NET 5 并使用现在必须在 Startup.cs 类中配置的部分时,我不会在两个看起来相关的不同类中进行依赖注入和其他配置到启动和配置。

Startup.Configuration gets called slightly later than Application_Start, but I don't think the difference will matter much in most cases. Startup.Configuration 的调用时间比 Application_Start 稍晚,但我认为在大多数情况下差异并不重要。

I believe the major reasons we kept the other code in Global.asax are:我相信我们在 Global.asax 中保留其他代码的主要原因是:

  1. Consistency with previous versions of MVC.与以前版本的 MVC 保持一致。 (That's where everybody currently expects to find this code.) (这是目前每个人都希望找到此代码的地方。)
  2. Ability to add other event handlers.能够添加其他事件处理程序。 In Global.asax, you can handle other methods like Session_Start and Application_Error.在 Global.asax 中,您可以处理其他方法,如 Session_Start 和 Application_Error。
  3. Correctness in a variety of authentication scenarios.在各种身份验证场景中的正确性。 The Startup.Configuration method is only called if you have Microsoft.Owin.Host.SystemWeb.dll in your bin directory.仅当 bin 目录中有 Microsoft.Owin.Host.SystemWeb.dll 时才会调用 Startup.Configuration 方法。 If you remove this DLL, it will silently stop calling Startup.Configuration, which could be hard to understand.如果您删除此 DLL,它将默默地停止调用 Startup.Configuration,这可能很难理解。

I think the third reason is the most important one we didn't take this approach by default, since some scenarios don't include having this DLL, and it's nice to be able to change authentication approaches without invalidating the location where unrelated code (like route registration) is placed.我认为第三个原因是我们默认没有采用这种方法的最重要的一个,因为有些场景不包括这个 DLL,并且能够更改身份验证方法而不会使不相关代码的位置无效(例如路线注册)放置。

But if none of those reasons apply in your scenario, I think you'd be fine using this approach.但是,如果这些原因都不适用于您的场景,我认为您可以使用这种方法。

For those looking for the complete steps: If you are looking to create a OWIN based, IIS hosted web API, these steps should get you there:对于那些正在寻找完整步骤的人:如果您正在寻找创建基于 OWIN 的、由 IIS 托管的 Web API,这些步骤应该可以帮助您:

  1. File -> New -> Project
  2. In the dialogue, Installed -> templates -> Other Project types -> Visual Studio Solutions -> Blank Solution targeting .NET 4.6在对话框中, Installed -> templates -> Other Project types -> Visual Studio Solutions -> Blank Solution targeting .NET 4.6
  3. On the solution, right click, add Project -> Web -> ASP.NET Web Application (targeting .NET 4.6)在解决方案上,右键单击,添加Project -> Web -> ASP.NET Web Application (targeting .NET 4.6)

    3.1 Now In the ASP.NET 4.5 templates, choose Empty as the template 3.1 现在在 ASP.NET 4.5 模板中,选择 Empty 作为模板

    3.2 This creates a blank solution with two nuget packages: 3.2 这将创建一个包含两个 nuget 包的空白解决方案:

     Microsoft.CodeDom.Providers.DotNetCompilerPlatform v 1.0.0 Microsoft.Net.Compilers v 1.0.0
  4. Install the following packages:安装以下软件包:

     Install-Package Microsoft.AspNet.WebApi.WebHost -Version 5.2.3 Install-Package Microsoft.AspNet.WebApi -Version 5.2.3 Install-Package WebApiContrib.Formatting.Razor 2.3.0.0

For OWIN:对于 OWIN:

Install-Package Microsoft.Owin.Host.SystemWeb 
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost    

Then add Startup.cs with Configuration method:然后使用 Configuration 方法添加 Startup.cs:

[assembly:OwinStartup(typeof(namespace.Startup))]
public class Startup
    {
        /// <summary> Configurations the specified application. </summary>
        /// <param name="app">The application.</param>
        public static void Configuration(IAppBuilder app)
        {
            var httpConfiguration = CreateHttpConfiguration();

            app
                .UseWebApi(httpConfiguration);
        }

        /// <summary> Creates the HTTP configuration. </summary>
        /// <returns> An <see cref="HttpConfiguration"/> to bootstrap the hosted API </returns>
        public static HttpConfiguration CreateHttpConfiguration()
        {
            var httpConfiguration = new HttpConfiguration();
            httpConfiguration.MapHttpAttributeRoutes();

            return httpConfiguration;
        }
}

Now add a class that inherits from ApiController , annotate it with RoutePrefix attribute and the action method with Route + HttpGet/PutPost (representing the Http verb you're after) and you should be good to go现在添加一个继承自ApiController的类,使用RoutePrefix属性对其进行注释,并使用Route + HttpGet/PutPost (代表您要使用的 Http 动词) Route + HttpGet/PutPost的操作方法进行注释, RoutePrefix就可以开始使用了

This is my understanding of how starting/hosting a web application evolved as it's all pretty confusing to follow.这是我对启动/托管 Web 应用程序如何演变的理解,因为它非常令人困惑。 A small summary:一个小总结:

1. Classic ASP.NET: Write only the application code to run in the last step of the mandatory IIS pipeline 1.经典ASP.NET:只编写应用程序代码在强制IIS管道的最后一步运行

2. ASP.NET with OWIN: Configure a .NET webserver and write your application code. 2. 使用 OWIN 的 ASP.NET:配置 .NET 网络服务器并编写您的应用程序代码。 No longer directly coupled to IIS, so you're no longer forced to use it.不再直接耦合到 IIS,因此您不再被迫使用它。

3. ASP.NET Core: Configure both the host and the webserver to use and write your application code. 3. ASP.NET Core:配置主机和网络服务器以使用和编写您的应用程序代码。 No longer mandatatory to use a .NET webserver if you target .NET Core instead of the full .NET Framework.如果您的目标是 .NET Core 而不是完整的 .NET Framework,则不再强制要求使用 .NET Web 服务器。


Now I'll go a bit more into detail of how it works and which classes are used to start the application:现在我将更详细地介绍它的工作原理以及使用哪些类来启动应用程序:

Classic ASP.NET经典的 ASP.NET

Classic ASP.NET applications have the Global.asax file as entry point.经典的 ASP.NET 应用程序将Global.asax文件作为入口点。 These applications can only be run in IIS and your code gets executed at the end of the IIS pipeline (so IIS is responsible for CORS, authentication... before your code even runs).这些应用程序只能在 IIS 中运行,并且您的代码在 IIS 管道的末尾执行(因此 IIS 负责 CORS、身份验证......甚至在您的代码运行之前)。 Since IIS 7 you can run your application in integrated mode which integrates the ASP.NET runtime into IIS.从 IIS 7 开始,您可以在集成模式下运行您的应用程序,该模式将 ASP.NET 运行时集成到 IIS 中。 This enables your code to configure functionality which wasn't possible before (or only in IIS itself) such as url rewriting in the Application_Start event of your Global.asax file or use the new <system.webserver> section in your web.config file.这使您的代码能够配置以前(或仅在 IIS 本身中)无法实现的功能,例如在Global.asax文件的Application_Start事件中重写 url或使用web.config文件中的新<system.webserver>部分.

ASP.NET with OWIN使用 OWIN 的 ASP.NET

First of all OWIN is not a library but a specification of how .NET web servers (for example IIS) interact with web applications.首先, OWIN不是一个库,而是 .NET Web 服务器(例如 IIS)如何与 Web 应用程序交互的规范。 Microsoft themselves have an implementation of OWIN called project Katana (distributed through several different NuGet packages).微软自己有一个名为项目 Katana的 OWIN 实现(通过几个不同的 NuGet 包分发)。 This implementation provides the IAppBuilder interface you encounter in a Startup class and some OWIN middleware components (OMC's) provided by Microsoft.此实现提供了您在Startup类中遇到的IAppBuilder接口和 Microsoft 提供的一些 OWIN 中间件组件 (OMC)。 Using IAppBuilder you basically compose middleware in a plug-and-play way to create the pipeline for the webserver (in addition to only the ASP.NET pipeline in IIS7+ as in the point above) instead of being tied to the IIS pipeline (but now you use a middleware component for CORS, a middleware component for authentication...).使用IAppBuilder您基本上以即插即用的方式组合中间件来为网络服务器创建管道(除了上面提到的 IIS7+ 中的 ASP.NET 管道),而不是绑定到 IIS 管道(但现在您使用一个用于 CORS 的中间件组件,一个用于身份验证的中间件组件......)。 Because of this, your application is not specifically coupled to IIS anymore and you can run it on any .NET Webserver, for example:因此,您的应用程序不再专门与 IIS 耦合,您可以在任何 .NET Web 服务器上运行它,例如:

  • The OwinHost package can be used to self-host your application with a Katana webserver. OwinHost包可用于通过 Katana 网络服务器自托管您的应用程序。
  • The Microsoft.Owin.Host.SystemWeb package is used to host your OWIN application in IIS7+ in integrated mode, by subscribing your middleware to the correct lifetime events internally. Microsoft.Owin.Host.SystemWeb包用于在集成模式下在 IIS7+ 中托管您的 OWIN 应用程序,方法是在内部为您的中间件订阅正确的生命周期事件。

The thing that makes everything so confusing is that Global.asax is still supported together with the OWIN Startup class, while they can both do similar things.使一切变得如此混乱的事情是Global.asax仍然与 OWIN Startup类一起受支持,而它们都可以做类似的事情。 For example you could implement CORS in Global.asax and authentication using OWIN middleware which becomes really confusing.例如,您可以在Global.asax实现 CORS 并使用 OWIN 中间件进行身份验证,这会变得非常混乱。

My rule of thumb is to remove the Global.asax file alltogether in favor of using Startup whenever I need to add OWIN.我的经验法则是在需要添加 OWIN 时将Global.asax文件全部删除,以支持使用Startup

ASP.NET Core ASP.NET 核心

ASP.NET Core is the next evolution and now you can target either .NET Core or the full .NET Framework. ASP.NET Core 是下一个演变,现在您可以面向 .NET Core 或完整的 .NET Framework。 When you target .NET Core you can run your application on any host which supports the .NET Standard.当您以 .NET Core 为目标时,您可以在任何支持 .NET Standard 的主机上运行您的应用程序。 This means you are no longer restricted to a .NET webserver (as in the previous point), but can host your application in Docker containers, a linux webserver, IIS...这意味着您不再局限于 .NET 网络服务器(如上一点),而是可以在 Docker 容器、Linux 网络服务器、IIS 中托管您的应用程序......

The entry point for an ASP.NET Core web application is the Program.cs file. ASP.NET Core Web 应用程序的入口点是Program.cs文件。 There you configure your host and again specify your Startup class where you configure your pipeline.在那里配置您的主机并再次指定您配置管道的Startup类。 Using OWIN (by using the IAppBuilder.UseOwin extension method) is optional, but fully supported .使用 OWIN(通过使用IAppBuilder.UseOwin扩展方法)是可选的,但完全受支持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 OWIN和Global.asax.cs文件 - OWIN and Global.asax.cs file 如何使服务器使用startup.cs而不是Global.asax.cs - How to make the server use the startup.cs instead of Global.asax.cs 在 Azure Function 中引用类库 .dll 文件,是否需要在 Startup.cs 中设置服务? - Referencing class library .dll file in Azure Function, do I need to setup the services in Startup.cs? 将Global.asax迁移到Startup.cs - Migrate Global.asax to Startup.cs Global.asax.cs 文件在哪里? - Where is the Global.asax.cs file? 有什么方法可以将owin startup.cs配置为在全局asax应用程序启动之前运行? - Is there any way to configure owin startup.cs to be run before global asax application start? MissingMethodException Global.asax.cs - MissingMethodException Global.asax.cs global.asax.cs授权webapi事件需要锁定吗? - global.asax.cs authorize events for webapi need lock? 如何使用 Blazor 从 .CS 文件而不是 .RAZOR 文件访问在 Startup.cs 中注释的范围服务中的数据? - How do I access data within a scoped service, annotated in Startup.cs, from a .CS file NOT a .RAZOR file using Blazor? Starts..c中的Global.asax Application_Error等价物 - Global.asax Application_Error equivalent in Startup.cs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM