從ASP.NET到ASP.NET Core差異變化


MSDN原文:鏈接

ASP.NET Core項目為開發人員提供了針對.NET Core,.NET Framework2種實現方式,根據官網通告NETCORE3.0后將取消對.NET Framework的支持。

NET Framework下使用

在針對.NET Framework時,項目需要引用NuGet AspNetCore包。

<ItemGroup>
   <PackageReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

 

項目結構差異:

.csproj的文件在ASP.NET Core下進行了簡化:

  • 明確包含文件不是他們被視為項目的一部分。這可以降低在處理大型團隊時出現XML合並沖突的風險。

  • 沒有其他項目的基於GUID的引用,這提高了文件的可讀性。

  • 可以在不在Visual Studio中卸載文件的情況下編輯該文件 

 程序入口和Global.asax文件變更:

     ASP.NET Core引入了新的引導應用程序機制,ASP.NET 中入口點是Global.asax文件。路徑配置和過濾器以及區域注冊等任務在Global.asax文件中處理

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

此方法以干擾實現的方式將應用程序與其部署的服務器耦合在一起。為了解耦,OWIN被引入以提供一種更清晰的方式來一起使用多個框架。OWIN提供了一個管道,只添加所需的模塊。托管環境采用Startup功能來配置服務和應用程序的請求管道。

使用ASP.NET Core 后,應用程序的入口點是Startup,不再依賴Global.asax。

ASP.NET CORE  +NET Framework 實現(這會配置您的默認路由,默認為Json上的XmlSerialization。根據需要將其他中間件添加到此管道(加載服務,配置設置,靜態文件等):

using Owin;
using System.Web.Http;

namespace WebApi
{
    // Note: By default all requests go through this OWIN pipeline. Alternatively you can turn this off by adding an appSetting owin:AutomaticAppStartup with value “false”. 
    // With this turned off you can still have OWIN apps listening on specific routes by adding routes in global.asax file using MapOwinPath or MapOwinRoute extensions on RouteTable.Routes
    public class Startup
    {
        // Invoked once at startup to configure your application.
        public void Configuration(IAppBuilder builder)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute("Default", "{controller}/{customerID}", new { controller = "Customer", customerID = RouteParameter.Optional });

            config.Formatters.XmlFormatter.UseXmlSerializer = true;
            config.Formatters.Remove(config.Formatters.JsonFormatter);
            // config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;

            builder.UseWebApi(config);
        }
    }
}

 

ASP.NET CORE+Net Core實現中使用類似的方法,但不依賴於OWIN,相反,通過Program.cs Main方法(類似於控制台應用程序)完成的,並通過Startup加載。

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace WebApplication2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

 

Startup必須包括一種Configure方法。Configure,向管道添加必要的中間件。在以下示例中(來自默認網站模板),擴展方法配置管道,並支持:

  • 錯誤頁面
  • HTTP嚴格傳輸安全性
  • HTTP重定向到HTTPS
  • ASP.NET核心MVC 
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
}

Appliction和Host已經分離,這為遷移到不同平台提供了靈活性。

配置文件差異:

ASP.NET支持存儲配置。例如,這些設置用於支持部署應用程序的環境。通常的做法是將所有自定義鍵值對存儲<appSettings>Web.config文件部分中

<appSettings>
  <add key="UserName" value="User" />
  <add key="Password" value="Password" />
</appSettings>

 

ASP.NET 應用程序使用命名空間中ConfigurationManager.AppSettings集合讀取這些設置System.Configuration

string userName = System.Web.Configuration.ConfigurationManager.AppSettings["UserName"];
string password = System.Web.Configuration.ConfigurationManager.AppSettings["Password"];

 

ASP.NET Core可以將應用程序的配置數據存儲在任何文件中,並將其作為中間件引導的一部分加載。項目模板中使用的默認文件是appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  // Here is where you can supply custom configuration settings, Since it is is JSON, everything is represented as key: value pairs
  // Name of section is your choice
  "AppConfiguration": {
    "UserName": "UserName",
    "Password": "Password"
  }
}

通過Startup.csappsettings.json文件加載到IConfiguration應用程序內部的實例中

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

讀取Configuration以獲取設置

string userName = Configuration.GetSection("AppConfiguration")["UserName"];
string password = Configuration.GetSection("AppConfiguration")["Password"];

對於更深入的參考ASP.NET Core配置,請查看 在ASP.NET核心配置

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM