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

MSDN原文:連接
json

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

NET Framework下使用服務器

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

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

 

項目結構差別:

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

  • 明確包含文件不是他們被視爲項目的一部分。這能夠下降在處理大型團隊時出現XML合併衝突的風險。框架

  • 沒有其餘項目的基於GUID的引用,這提升了文件的可讀性。網站

  • 能夠在不在Visual Studio中卸載文件的狀況下編輯該文件 ui

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

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

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功能來配置服務和應用程序的請求管道。spa

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

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核心配置

相關文章
相關標籤/搜索