在本文中,我們會逐步引導您將現有的 ASP.NET Core 1.x 專案更新到 ASP.NET Core 2.0。 將應用程式移轉至 ASP.NET Core 2.0 可讓您利用 許多新功能和效能改善。
現有的 ASP.NET Core 1.x 應用程式是以版本特定專案範本為基礎。 隨著 ASP.NET Core 架構的發展,專案範本和其中所包含的入門程式代碼也是如此。 除了更新 ASP.NET Core 架構之外,您還需要更新應用程式的程式代碼。
先決條件
請參閱 開始使用 ASP.NET Core。
更新目標框架標識(TFM)
以 .NET Core 為目標的項目應該使用大於或等於 .NET Core 2.0 版本的 TFM 。 在<TargetFramework>
檔案中搜尋.csproj
節點,並將其內部文字替換為netcoreapp2.0
:
<TargetFramework>netcoreapp2.0</TargetFramework>
以 .NET Framework 為目標的項目應該使用大於或等於 .NET Framework 4.6.1 版本的 TFM。 在<TargetFramework>
檔案中搜尋.csproj
節點,並將其內部文字替換為net461
:
<TargetFramework>net461</TargetFramework>
備註
.NET Core 2.0 提供比 .NET Core 1.x 更廣泛的功能範圍。 如果您僅僅因為 .NET Core 1.x 缺少的 API 而選擇使用 .NET Framework,那麼使用 .NET Core 2.0 很可能就可以正常運行。
如果項目檔包含 <RuntimeFrameworkVersion>1.{sub-version}</RuntimeFrameworkVersion>
,請參閱 此 GitHub 問題。
更新 global.json 中的 .NET Core SDK 版本
如果您的解決方案依賴檔案 global.json 以特定 .NET Core SDK 版本為目標,請更新其 version
屬性以使用您電腦上安裝的 2.0 版本:
{
"sdk": {
"version": "2.0.0"
}
}
更新套件參考
.csproj
1.x 專案中的檔案會列出專案所使用的每個 NuGet 套件。
在以 .NET Core 2.0 為目標的 ASP.NET Core 2.0 專案中,檔案中的單一.csproj
參考會取代套件集合:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
</ItemGroup>
ASP.NET Core 2.0 和 Entity Framework Core 2.0 的所有功能都包含在中繼套件中。
ASP.NET 以 .NET Framework 為目標的Core 2.0項目應該會繼續參考個別的 NuGet 套件。 將 Version
每個 <PackageReference />
節點的屬性更新為 2.0.0。
例如,以下是以 .NET Framework 為目標的典型 ASP.NET Core 2.0 專案中所使用的節點清單 <PackageReference />
:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" PrivateAssets="All" />
</ItemGroup>
Microsoft.Extensions.CommandLineUtils
套件已淘汰。 它仍然可用,但不受支援。
更新 .NET CLI 工具
在 .csproj
檔案中,將每個 Version
節點的 <DotNetCliToolReference />
屬性更新為 2.0.0。
例如,以下是以 .NET Core 2.0 為目標的典型 ASP.NET Core 2.0 專案中使用的 CLI 工具清單:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
重新命名套件目標後援屬性
.csproj
1.x 項目的檔案使用PackageTargetFallback
節點和變數:
<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
將節點與變數重新命名為 AssetTargetFallback
:
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
更新 Program.cs 中的 Main 方法
在 1.x 專案中, Main
的 Program.cs
方法看起來像這樣:
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace AspNetCoreDotNetCore1App
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
在 2.0 專案中,Main
的方法已被簡化使用Program.cs
:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace AspNetCoreDotNetCore2App
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
強烈建議採用新版 2.0 模式,因為產品功能如 Entity Framework (EF) Core 移轉 需要此模式才能正常運作。 例如, Update-Database
從 [套件管理員控制台] 視窗或 dotnet ef database update
命令行執行 (在轉換成 ASP.NET Core 2.0 的專案上)會產生下列錯誤:
Unable to create an object of type '<Context>'. Add an implementation of 'IDesignTimeDbContextFactory<Context>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
新增組態提供者
在 1.x 專案中,應用程式透過建構函式新增組態提供者。 建立 實例 ConfigurationBuilder
、載入適用的提供者(環境變數、應用程式設定等),以及初始化 成員 IConfigurationRoot
的步驟。
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
上述範例會將Configuration
成員載入,該成員具備appsettings.json
的組態設定,同時載入任何符合appsettings.{Environment}.json
屬性的IHostingEnvironment.EnvironmentName
檔案。 這些檔案的位置是在與Startup.cs
相同的路徑上。
在 2.0 專案中,1.x 專案固有的未定案組態程式代碼會在幕後執行。 例如,環境變數和應用程式設定會在啟動時載入。 對等 Startup.cs
程式代碼會縮減為 IConfiguration
使用插入的實例進行初始化:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
若要移除 WebHostBuilder.CreateDefaultBuilder
新增的預設提供者,請在 Clear
裡對 IConfigurationBuilder.Sources
屬性呼叫 ConfigureAppConfiguration
方法。 若要將提供者新增回,請使用 ConfigureAppConfiguration
中的 Program.cs
方法:
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureAppConfiguration((hostContext, config) =>
{
// delete all default configuration providers
config.Sources.Clear();
config.AddJsonFile("myconfig.json", optional: true);
})
.Build();
CreateDefaultBuilder
看到上述代碼段中 方法所使用的組態。
如需詳細資訊,請參閱 ASP.NET Core 中的組態。
移動資料庫初始化代碼
在 1.x 專案中使用 EF Core 1.x 的命令,如 dotnet ef migrations add
,會執行以下操作:
- 具現化
Startup
實例 -
ConfigureServices
呼叫方法來註冊所有服務到相依性注入(包括DbContext
類型) - 執行其必要工作
在使用 EF Core 2.0 的 2.0 專案中, Program.BuildWebHost
會叫用 以取得應用程式服務。 不同於 1.x,這具有叫用 Startup.Configure
的額外副作用。 如果您的 1.x 應用程式在其 Configure
方法中叫用資料庫初始化程式代碼,可能會發生非預期的問題。 例如,如果資料庫還不存在,則植入程序代碼會在 EF Core Migrations 命令執行之前執行。 如果資料庫還不存在,此問題會導致 dotnet ef migrations list
命令失敗。
在Configure
的方法Startup.cs
中,請考慮以下 1.x 種子初始化程式代碼:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
SeedData.Initialize(app.ApplicationServices);
在 2.0 專案中,將 SeedData.Initialize
呼叫移至 Main
的 方法 Program.cs
:
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
// Requires using RazorPagesMovie.Models;
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
從 2.0 版本起,在 BuildWebHost
中執行除建置和設定 Web 主機之外的任何行為都被視為不當的做法。 執行應用程式的任何項目都應該在BuildWebHost
之外處理,通常是在Main
的Program.cs
方法中。
檢視 Razor 編譯設定
更快速的應用程式啟動時間和較小的已發佈套件組合對於您至關重要。 基於這些原因, Razor 在 Core 2.0 ASP.NET 預設會啟用檢視編譯。
不再需要將 MvcRazorCompileOnPublish
屬性設定為 true。 除非您停用檢視編譯,否則屬性可能會從 .csproj
檔案中移除。
以 .NET Framework 為目標時,您仍然需要在Razor檔案中明確參考Microsoft.AspNetCore.Mvc.ViewCompilation NuGet 套件。
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.0.0" PrivateAssets="All" />
依賴 Application Insights「亮起」功能
應用程式效能檢測的輕鬆設定很重要。 您現在可以依賴 Visual Studio 2017 工具中可用的新 Application Insights 「亮起」功能。
ASP.NET Visual Studio 2017 中建立的 Core 1.1 項目預設會新增 Application Insights。 如果您不是直接使用 Application Insights SDK,而是在 Program.cs
和 Startup.cs
外部使用,請遵循下列步驟:
如果以 .NET Core 為目標,請從
<PackageReference />
檔案中移除下列.csproj
節點:<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
如果以 .NET Core 為目標,請從
UseApplicationInsights
移除Program.cs
擴充方法的呼叫:public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .Build(); host.Run(); }
從
_Layout.cshtml
移除 Application Insights 用戶端 API 呼叫。 包含下列兩行程式代碼:@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet @Html.Raw(JavaScriptSnippet.FullScript)
如果您直接使用 Application Insights SDK,請繼續這麼做。 2.0 中繼套件 包含最新版的 Application Insights,因此,如果您參考舊版,就會顯示套件降級錯誤。
採用驗證/Identity 的改進措施
ASP.NET Core 2.0 具有新的驗證模型,以及 ASP.NET Core Identity的一些重大變更。 如果您已建立已啟用個別使用者帳戶的專案,或已手動新增驗證或 Identity,請參閱 如何將驗證和 Identity 移轉到 ASP.NET Core 2.0。