本文說明如何開始將 ASP.NET MVC 專案移轉至 ASP.NET Core MVC。 在此過程中,它會突顯來自 ASP.NET MVC 的相關變更。
從 ASP.NET MVC 移轉是一個多階段的過程。 本文涵蓋:
- 初步設定。
- 基本控制器和視圖。
- 靜態內容。
- 客戶端依賴性。
Prerequisites
- Visual Studio 2019 16.4 或更新版本,其中包含 ASP.NET 和網頁程式開發工作負載
- .NET Core 3.1 SDK
建立入門 ASP.NET MVC 專案
在 Visual Studio 中建立 ASP.NET MVC 專案的範例以移轉:
- 從 [檔案] 功能表選取 [新增]>[專案]。
- 選取 [ASP.NET Web 應用程式 [.NET Framework], 然後選取 [ 下一步]。
- 將專案命名為 WebApp1 ,使命名空間與下一步建立的 ASP.NET Core 專案相符。 選取 ,創建。
- 選擇 MVC,然後選擇 建立。
建立 ASP.NET Core 專案
使用新的 ASP.NET Core 專案建立新的解決方案,以移轉至:
- 啟動 Visual Studio 的第二個實例。
- 從 [檔案] 功能表選取 [新增]>[專案]。
- 選取 [ASP.NET Core Web 應用程式 ],然後選取 [ 下一步]。
- 在 [ 設定新專案 ] 對話框中,將專案命名為 WebApp1。
- 將位置設定為與上一個專案不同的目錄,以使用相同的項目名稱。 使用相同的命名空間可讓您更輕鬆地在兩個項目之間複製程序代碼。 選取 ,創建。
- 在 [[建立新的 ASP.NET Core Web 應用程式] 對話框中,確認已選取 .NET Core 和 ASP.NET Core 3.1。 選取 [Web 應用程式] [模型-View-Controller] 項目範本,然後選取 [ 建立]。
將 ASP.NET Core 網站設定為使用MVC
在 ASP.NET Core 3.0 或更新版本中,.NET Framework 不再是支援的目標架構。 您的項目必須以 .NET Core 為目標。 包含MVC的 ASP.NET Core 共用架構是 .NET Core 執行時間安裝的一部分。 在項目檔中使用 Microsoft.NET.Sdk.Web SDK 時,會自動參考共用架構:
<Project Sdk="Microsoft.NET.Sdk.Web">
欲了解更多資訊,請參閱框架參考。
在 ASP.NET Core 中,類別 Startup :
-
Global.asax已被取代。 - 處理所有應用程式啟動工作。
如需詳細資訊,請參閱 ASP.NET Core 中的應用程式啟動。
在 ASP.NET Core 專案中,開啟 Startup.cs 檔案:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ASP.NET Core 應用程式必須選擇使用中間件加入架構功能。 先前樣本產生的程式代碼會新增下列服務和中間件:
- 擴充 AddControllersWithViews 方法會將 MVC 服務支援註冊到控制器、API 相關功能以及檢視中。 如需MVC服務註冊選項的詳細資訊,請參閱 MVC服務註冊
- 擴充 UseStaticFiles 方法會新增靜態檔案處理程式
Microsoft.AspNetCore.StaticFiles。 必須先呼叫UseStaticFiles擴充方法,再執行UseRouting。 如需詳細資訊,請參閱 ASP.NET Core 中的靜態檔案。 - 擴充 UseRouting 方法會新增路由。 如需詳細資訊,請參閱 ASP.NET Core 中的路線規劃。
此現有組態包含移轉範例 ASP.NET MVC 專案所需的專案。 如需 ASP.NET Core 中間件選項的詳細資訊,請參閱 ASP.NET Core 中的應用程式啟動。
遷移控制器和視圖
在 ASP.NET Core 專案中,會新增一個新的空控制器類別和一個新的空檢視類別,作為佔位元,並使用與要從中移轉的任何 ASP.NET MVC 專案中的控制器和檢視類別相同的名稱。
ASP.NET Core WebApp1 專案已包含一個與 ASP.NET MVC 專案同名的最小範例控制器與檢視。 因此,這些將作為從 ASP.NET MVC WebApp1 專案中待遷移的 ASP.NET MVC 控制器和視圖的佔位符。
- 從 ASP.NET MVC
HomeController複製方法,以取代新的 ASP.NET CoreHomeController方法。 不需要變更動作方法的傳回類型。 ASP.NET MVC 內建範本的控制器動作方法傳回類型為 ActionResult;ASP.NET Core MVC 中,動作方法會改為傳回IActionResult。ActionResult實現IActionResult。 - 在 ASP.NET Core 專案中,右鍵點擊 Views/Home 目錄,選擇 新增>現有項目。
- 在 [ 新增現有專案] 對話框中,流覽至 ASP.NET MVC WebApp1 專案的 Views/Home 目錄。
- 選擇
About.cshtml、Contact.cshtml,並Index.cshtmlRazor 檢視檔案,然後選擇 新增,取代現有檔案。
如需詳細資訊,請參閱 在 ASP.NET Core MVC 中使用控制器處理要求 和 ASP.NET Core MVC 中的檢視。
測試每個方法
每一個控制器端點都可以測試,而版面配置和樣式在文件後面會提到。
- 執行 ASP.NET Core 應用程式。
- 從執行中的 ASP.NET Core 應用程式的瀏覽器叫用已轉譯的檢視,方法是將瀏覽器中的目前埠號碼替換為 ASP.NET Core 專案使用的埠號碼。 例如:
https://localhost:44375/home/about。
移轉靜態內容
在 ASP.NET MVC 5 或更早版本中,靜態內容是從 Web 專案的根目錄裝載,並與伺服器端檔案混用。 在 ASP.NET Core 中,靜態檔案會儲存在專案的 網頁根 目錄中。 默認目錄為 {content root}/wwwroot,但可以變更。 如需詳細資訊,請參閱 ASP.NET Core 中的靜態檔案。
將 ASP.NET MVC WebApp1 專案的靜態內容複製到 ASP.NET Core wwwroot 專案的目錄:
- 在 ASP.NET Core 專案中,右鍵點擊
wwwroot目錄,選擇 新增>現有項目。 - 在 [ 新增現有專案] 對話框中,流覽至 ASP.NET MVC WebApp1 專案。
- 選擇檔案,
favicon.ico然後選擇 新增,取代現有檔案。
移轉版面配置檔案
將 ASP.NET MVC 專案設定檔複製到 ASP.NET Core 專案:
- 在 ASP.NET Core 專案中,右鍵點擊
Views目錄,選擇 新增>現有項目。 - 在 [ 新增現有專案] 對話框中,流覽至 ASP.NET MVC WebApp1 項目的
Views目錄。 - 請先選擇
_ViewStart.cshtml檔案,然後再選擇新增。
將 ASP.NET MVC 專案分享版面設定檔案複製到 ASP.NET Core 專案:
- 在 ASP.NET Core 專案中,右鍵點擊
Views/Shared目錄,選擇 新增>現有項目。 - 在 [ 新增現有專案] 對話框中,流覽至 ASP.NET MVC WebApp1 項目的
Views/Shared目錄。 - 選擇檔案,
_Layout.cshtml然後選擇 新增,取代現有檔案。
在 ASP.NET Core 專案中,開啟 _Layout.cshtml 檔案。 進行下列變更,以符合如下所示的已完成程序代碼:
更新 Bootstrap CSS 的引用,以符合下列已完成的代碼:
- 將
@Styles.Render("~/Content/css")替換成一個<link>元素以載入bootstrap.css(請參閱下方)。 - 移除
@Scripts.Render("~/bundles/modernizr")。
Bootstrap CSS 的替換標記已完成:
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
更新 jQuery 和 Bootstrap JavaScript 包含,以符合下列已完成的程式代碼:
- 將取代
@Scripts.Render("~/bundles/jquery")為<script>元素(請參閱下方)。 - 將取代
@Scripts.Render("~/bundles/bootstrap")為<script>元素(請參閱下方)。
jQuery 和 Bootstrap JavaScript 的完整替換標記:
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
更新 _Layout.cshtml 的檔案如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
@RenderSection("scripts", required: false)
</body>
</html>
在瀏覽器中檢視網站。 它應該以預期的樣式呈現。
設定統合和縮製
ASP.NET Core 相容於多個開源的捆綁與縮小解決方案,如 WebOptimizer 及其他類似函式庫。 ASP.NET Core 不提供原生統合和縮製解決方案。 如需設定統合和縮減的資訊,請參閱 統合和縮製。
解決 HTTP 500 錯誤
有許多問題可能會導致 HTTP 500 錯誤訊息,其中包含沒有問題來源的資訊。 例如,如果 Views/_ViewImports.cshtml 檔案包含專案中不存在的命名空間,就會產生 HTTP 500 錯誤。 在 ASP.NET Core 應用程式中,預設會將 UseDeveloperExceptionPage 擴充功能新增至 IApplicationBuilder,並在環境為 開發 時執行。 這在下列程式代碼中詳述:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ASP.NET Core 會將未處理的例外狀況轉換成 HTTP 500 錯誤回應。 通常,錯誤詳細數據不會包含在這些回應中,以防止洩漏伺服器的潛在敏感性資訊。 如需詳細資訊,請參閱 開發人員例外狀況頁面。
後續步驟
- <identity.md>
其他資源
本文說明如何開始將 ASP.NET MVC 專案移轉至 ASP.NET Core MVC 2.2。 在這個過程中,它會強調許多從 ASP.NET MVC 變更的內容。 從 ASP.NET MVC 移轉是一個多階段的過程。 本文涵蓋:
- 初始設定
- 基本控制器和視圖
- 靜態內容
- 客戶端依賴性
如需移轉組態和 Identity 程序代碼,請參閱 <configuration.md> 和 <identity.md>。
Note
範例中的版本號碼可能不是最新的,請據以更新專案。
建立入門 ASP.NET MVC 專案
為了示範升級,我們將從建立 ASP.NET MVC應用程式開始。 用 WebApp1 名稱建立,這樣命名空間就會跟下一步建立的 ASP.NET Core 專案相符。
隨意的: 將解決方案名稱從 WebApp1 改為 Mvc5。 Visual Studio 顯示新的解決方案名稱(Mvc5),方便區分這個專案和下一個專案。
建立 ASP.NET Core 專案
建立一個新的 空 ASP.NET Core 網頁應用程式,名稱與前一個專案相同(WebApp1),讓兩個專案的命名空間相符。 擁有相同的命名空間可讓您更輕鬆地在兩個項目之間複製程序代碼。 在與上一個專案不同的目錄中建立此專案,以使用相同的名稱。
- 隨意的: 使用 網頁應用 專案範本建立一個新的 ASP.NET Core 應用程式。 請為專案命名 WebApp1,並選擇「 個人使用者帳號」的認證選項。 將此應用程式重新命名為 FullAspNetCore。 建立此項目可節省轉換時間。 最終結果可以在範本產生的程式代碼中檢視、程式代碼可以複製到轉換專案,或與範本產生的項目比較。
將網站設定為使用MVC
- 針對 .NET Core 時,預設會參考 Microsoft.AspNetCore.App metapackage 。 此套件包含MVC應用程式常用的套件。 如果以 .NET Framework 為目標,則必須在專案檔中個別列出套件參考。
Microsoft.AspNetCore.Mvc 是核心MVC架構 ASP.NET。
Microsoft.AspNetCore.StaticFiles 是靜態檔案處理程式。 ASP.NET Core 應用程式明確選擇中間件,例如提供靜態檔案。 欲了解更多資訊,請參閱 靜態檔案。
- 開啟
Startup.cs檔案並變更程式碼以符合下列內容:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
擴充 UseStaticFiles 方法會新增靜態檔案處理程式。 欲了解更多資訊,請參閱 應用程式啟動 與 路由。
新增控制器和檢視
在本節中,將新增一個基本的控制器和檢視,用來作為下一節中要移轉的 ASP.NET MVC 控制器和檢視的佔位符。
Controllers新增目錄。將名為
HomeController.cs的控制器類別新增至Controllers目錄。
Views新增目錄。Views/Home新增目錄。將名為 Razor 的
Index.cshtml新增至目錄。
項目結構如下所示:
以下列標記取代 Views/Home/Index.cshtml 檔案的內容:
<h1>Hello world!</h1>
執行應用程式。
下列功能需要從範例 ASP.NET MVC 專案移轉至 ASP.NET Core 專案:
用戶端內容 (CSS、字型和腳稿)
controllers
views
models
統合
filters
登入/註銷( Identity 這是在下一個教學課程中完成的。)
控制器和視圖
將每個方法從 ASP.NET MVC
HomeController複製到新的HomeController。 在 ASP.NET MVC 中,內建範本的控制器動作方法傳回類型為 ActionResult;在 ASP.NET Core MVC 中,動作方法會改為傳回IActionResult。ActionResult會實作IActionResult,因此不需要變更動作方法的傳回類型。將
About.cshtml、Contact.cshtml和Index.cshtmlRazor 檢視檔案從 ASP.NET MVC 專案複製到 ASP.NET Core 專案。
測試每個方法
版面配置檔案和樣式尚未移轉,因此轉譯的檢視只會包含檢視檔案中的內容。 版面配置檔案為About和Contact檢視產生的連結尚無法使用。
在執行中的 ASP.NET Core 應用程式上,從瀏覽器叫用已呈現的視圖,方法是將目前的埠號碼替換成 ASP.NET Core 專案中使用的埠號碼。 例如: https://localhost:44375/home/about 。
請注意樣式和選單項目缺失。 下一節中將會修正樣式。
靜態內容
在 ASP.NET MVC 5 或更早版本中,靜態內容是從 Web 專案的根目錄裝載,並與伺服器端檔案混用。 在 ASP.NET Core 中,靜態內容會裝載於 wwwroot 目錄中。 將靜態內容從 ASP.NET MVC 應用程式複製到 wwwroot ASP.NET Core 專案中的目錄。 在這個範例轉換中:
- 將
favicon.ico檔案從 ASP.NET MVC 專案複製到wwwrootASP.NET Core 專案中的 目錄。
ASP.NET MVC 專案使用 Bootstrap 進行樣式設計,並將 Bootstrap 檔案儲存在 Content and Scripts 目錄中。 產生 ASP.NET MVC 專案的範本會參考版面配置檔 (Views/Shared/_Layout.cshtml) 中的 Bootstrap。 可以將 bootstrap.js 和 bootstrap.css 檔案從 ASP.NET MVC 專案複製到新專案中的 wwwroot 目錄中。 相反地,本檔會在下一節中新增對使用 CDN 的 Bootstrap(和其他客戶端連結庫)的支援。
移轉版面配置檔案
_ViewStart.cshtml將檔案從 ASP.NET MVC 專案的Views目錄複製到 ASP.NET Core 專案的Views目錄中。 ASP.NET Core MVC 中,檔案_ViewStart.cshtml尚未變更。建立
Views/Shared目錄。隨意的:從
_ViewImports.cshtmlMVC 專案的目錄複製Views到 ASP.NET Core 專案的Views目錄。 拿掉檔案中的任何_ViewImports.cshtml命名空間宣告。 該_ViewImports.cshtml檔案為所有檢視檔案提供命名空間,並引入 標籤輔助功能。 標籤輔助器會用於新版面配置檔中。 檔案_ViewImports.cshtml是 ASP.NET Core 中的新檔案。_Layout.cshtml將檔案從 ASP.NET MVC 專案的Views/Shared目錄複製到 ASP.NET Core 專案的Views/Shared目錄中。
開啟 _Layout.cshtml 檔案並進行下列變更(完成的程式代碼如下所示):
將
@Styles.Render("~/Content/css")替換成一個<link>元素以載入bootstrap.css(請參閱下方)。移除
@Scripts.Render("~/bundles/modernizr")。將
@Html.Partial("_LoginPartial")行註解掉(用@*...*@括住行)。 如需詳細資訊,請參閱 Identity將取代
@Scripts.Render("~/bundles/jquery")為<script>元素(請參閱下方)。將取代
@Scripts.Render("~/bundles/bootstrap")為<script>元素(請參閱下方)。
Bootstrap CSS 包含的替代標記:
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
jQuery 和 Bootstrap JavaScript 包含的替代標記:
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
更新 _Layout.cshtml 的檔案如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@*@Html.Partial("_LoginPartial")*@
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
@RenderSection("scripts", required: false)
</body>
</html>
在瀏覽器中檢視網站。 它現在應該會正確載入,並具有預期的樣式。
- 選擇性: 試用新的版面檔案。 複製 FullAspNetCore 專案的版面檔案。 新的版面檔案使用 Tag Helpers ,並有其他改進。
設定統合和縮製
如需如何設定統合和縮小的詳細資訊,請參閱 統合和縮小。
解決 HTTP 500 錯誤
可能會導致 HTTP 500 錯誤訊息的問題有很多,而這些訊息中並不包含問題來源的資訊。 例如,如果 Views/_ViewImports.cshtml 檔案包含專案中不存在的命名空間,就會產生 HTTP 500 錯誤。 預設情況下,在 ASP.NET Core 應用程式中,UseDeveloperExceptionPage 擴充功能會被加入到 IApplicationBuilder 並在設定為 開發時執行。 請參閱下列程式代碼中的範例:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ASP.NET Core 會將未處理的例外狀況轉換成 HTTP 500 錯誤回應。 通常,錯誤詳細數據不會包含在這些回應中,以防止洩漏伺服器的潛在敏感性資訊。 如需詳細資訊,請參閱 開發人員例外狀況頁面。
其他資源
本文說明如何開始將 ASP.NET MVC 專案移轉至 ASP.NET Core MVC 2.1。 在這個過程中,它會強調許多從 ASP.NET MVC 變更的內容。 從 ASP.NET MVC 移轉是一個多階段的過程。 本文涵蓋:
- 初始設定
- 基本控制器和視圖
- 靜態內容
- 客戶端相依性
Note
範例中的版本號碼可能不是最新的,請據以更新專案。
建立入門 ASP.NET MVC 專案
為了示範升級,我們將從建立 ASP.NET MVC應用程式開始。 用 WebApp1 名稱建立,這樣命名空間就會跟下一步建立的 ASP.NET Core 專案相符。
隨意的: 將解決方案名稱從 WebApp1 改為 Mvc5。 Visual Studio 顯示新的解決方案名稱(Mvc5),方便區分這個專案和下一個專案。
建立 ASP.NET Core 專案
建立一個新的 空 ASP.NET Core 網頁應用程式,名稱與前一個專案相同(WebApp1),讓兩個專案的命名空間相符。 擁有相同的命名空間可讓您更輕鬆地在兩個項目之間複製程序代碼。 在與上一個專案不同的目錄中建立此專案,以使用相同的名稱。
- 隨意的: 使用 網頁應用 專案範本建立一個新的 ASP.NET Core 應用程式。 請為專案命名 WebApp1,並選擇「 個人使用者帳號」的認證選項。 將此應用程式重新命名為 FullAspNetCore。 建立此項目可節省轉換時間。 最終結果可以在範本產生的程式代碼中檢視、程式代碼可以複製到轉換專案,或與範本產生的項目比較。
將網站設定為使用MVC
- 針對 .NET Core 時,預設會參考 Microsoft.AspNetCore.App metapackage 。 此套件包含MVC應用程式常用的套件。 如果以 .NET Framework 為目標,則必須在專案檔中個別列出套件參考。
Microsoft.AspNetCore.Mvc 是核心MVC架構 ASP.NET。
Microsoft.AspNetCore.StaticFiles 是靜態檔案處理程式。 ASP.NET Core 應用程式明確選擇中間件,例如提供靜態檔案。 欲了解更多資訊,請參閱 靜態檔案。
- 開啟
Startup.cs檔案並變更程式碼以符合下列內容:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
擴充 UseStaticFiles 方法會新增靜態檔案處理程式。 擴充 UseMvc 方法會新增路由。 欲了解更多資訊,請參閱 應用程式啟動 與 路由。
新增控制器和檢視
在本節中,將新增一個基本的控制器和檢視,用來作為下一節中要移轉的 ASP.NET MVC 控制器和檢視的佔位符。
Controllers新增目錄。在目錄中新增一個名為
HomeController.csControllers的控制器類別。
Views新增目錄。Views/Home新增目錄。將名為 Razor 的
Index.cshtml新增至目錄。
項目結構如下所示:
以下列標記取代 Views/Home/Index.cshtml 檔案的內容:
<h1>Hello world!</h1>
執行應用程式。
下列功能需要從範例 ASP.NET MVC 專案移轉至 ASP.NET Core 專案:
用戶端內容 (CSS、字型和腳稿)
controllers
views
models
統合
filters
登入/註銷( Identity 這是在下一個教學課程中完成的。)
控制器和視圖
將每個方法從 ASP.NET MVC
HomeController複製到新的HomeController。 在 ASP.NET MVC 中,內建範本的控制器動作方法傳回類型為 ActionResult;在 ASP.NET Core MVC 中,動作方法會改為傳回IActionResult。ActionResult會實作IActionResult,因此不需要變更動作方法的傳回類型。將
About.cshtml、Contact.cshtml和Index.cshtmlRazor 檢視檔案從 ASP.NET MVC 專案複製到 ASP.NET Core 專案。
測試每個方法
版面配置檔案和樣式尚未移轉,因此轉譯的檢視只會包含檢視檔案中的內容。 版面配置檔案為About和Contact檢視產生的連結尚無法使用。
- 在執行中的 ASP.NET Core 應用程式上,從瀏覽器叫用已呈現的視圖,方法是將目前的埠號碼替換成 ASP.NET Core 專案中使用的埠號碼。 例如:
https://localhost:44375/home/about。
請注意樣式和選單項目缺失。 下一節中將會修正樣式。
靜態內容
在 ASP.NET MVC 5 或更早版本中,靜態內容是從 Web 專案的根目錄裝載,並與伺服器端檔案混用。 在 ASP.NET Core 中,靜態內容會裝載於 wwwroot 目錄中。 將靜態內容從 ASP.NET MVC 應用程式複製到 wwwroot ASP.NET Core 專案中的目錄。 在這個範例轉換中:
- 將
favicon.ico檔案從 ASP.NET MVC 專案複製到wwwrootASP.NET Core 專案中的 目錄。
ASP.NET MVC 專案使用 Bootstrap 進行樣式設計,並將 Bootstrap 檔案儲存在 Content and Scripts 目錄中。 產生 ASP.NET MVC 專案的範本會參考版面配置檔 (Views/Shared/_Layout.cshtml) 中的 Bootstrap。 可以將 bootstrap.js 和 bootstrap.css 檔案從 ASP.NET MVC 專案複製到新專案中的 wwwroot 目錄中。 相反地,本檔會在下一節中新增對使用 CDN 的 Bootstrap(和其他客戶端連結庫)的支援。
移轉版面配置檔案
_ViewStart.cshtml將檔案從 ASP.NET MVC 專案的Views目錄複製到 ASP.NET Core 專案的Views目錄中。 ASP.NET Core MVC 中,檔案_ViewStart.cshtml尚未變更。建立
Views/Shared目錄。隨意的:從
_ViewImports.cshtmlMVC 專案的目錄複製Views到 ASP.NET Core 專案的Views目錄。 拿掉檔案中的任何_ViewImports.cshtml命名空間宣告。 該_ViewImports.cshtml檔案為所有檢視檔案提供命名空間,並引入 標籤輔助功能。 標籤輔助器會用於新版面配置檔中。 檔案_ViewImports.cshtml是 ASP.NET Core 中的新檔案。_Layout.cshtml將檔案從 ASP.NET MVC 專案的Views/Shared目錄複製到 ASP.NET Core 專案的Views/Shared目錄中。
開啟 _Layout.cshtml 檔案並進行下列變更(完成的程式代碼如下所示):
將
@Styles.Render("~/Content/css")替換成一個<link>元素以載入bootstrap.css(請參閱下方)。移除
@Scripts.Render("~/bundles/modernizr")。將
@Html.Partial("_LoginPartial")行註解掉(用@*...*@括住行)。 如需詳細資訊,請參閱 Identity將取代
@Scripts.Render("~/bundles/jquery")為<script>元素(請參閱下方)。將取代
@Scripts.Render("~/bundles/bootstrap")為<script>元素(請參閱下方)。
Bootstrap CSS 包含的替代標記:
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
jQuery 和 Bootstrap JavaScript 包含的替代標記:
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
更新 _Layout.cshtml 的檔案如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@*@Html.Partial("_LoginPartial")*@
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
@RenderSection("scripts", required: false)
</body>
</html>
在瀏覽器中檢視網站。 它現在應該會正確載入,並具有預期的樣式。
- 可選: 嘗試使用新的佈局檔案。 複製 FullAspNetCore 專案的版面檔案。 新的版面檔案使用 Tag Helpers ,並有其他改進。
設定統合和縮製
如需如何設定統合和縮小的詳細資訊,請參閱 統合和縮小。
解決 HTTP 500 錯誤
可能會導致 HTTP 500 錯誤訊息的問題有很多,而這些訊息中並不包含問題來源的資訊。 例如,如果 Views/_ViewImports.cshtml 檔案包含專案中不存在的命名空間,就會產生 HTTP 500 錯誤。 在 ASP.NET Core 應用程式中,預設情況下會將 UseDeveloperExceptionPage 擴展添加到 IApplicationBuilder,並在設定為 開發時執行。 請參閱下列程式代碼中的範例:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ASP.NET Core 會將未處理的例外狀況轉換成 HTTP 500 錯誤回應。 通常,錯誤詳細數據不會包含在這些回應中,以防止洩漏伺服器的潛在敏感性資訊。 如需詳細資訊,請參閱 開發人員例外狀況頁面。