建立可重複使用 UI 在 ASP.NET Core 中使用 Razor 類別庫專案Create reusable UI using the Razor class library project in ASP.NET Core

作者:Rick AndersonBy Rick Anderson

Razor 檢視、 頁面、 控制器、 頁面模型Razor 元件檢視元件,和資料模型可以建立 Razor 類別庫 (RCL)。Razor views, pages, controllers, page models, Razor components, View components, and data models can be built into a Razor class library (RCL). RCL 可以封裝和重複使用。The RCL can be packaged and reused. 應用程式可以包括 RCL,以及覆寫它所包含的檢視和頁面。Applications can include the RCL and override the views and pages it contains. 在 Web 應用程式和 RCL 中發現檢視、部分檢視,或是 Razor 頁面時,以 Web 應用程式中的 Razor 標記 ( .cshtml 檔案) 為優先。When a view, partial view, or Razor Page is found in both the web app and the RCL, the Razor markup (.cshtml file) in the web app takes precedence.

這項功能需要 .NET Core 2.1 SDK 或更新版本.NET Core 2.1 SDK or laterThis feature requires .NET Core 2.1 SDK 或更新版本.NET Core 2.1 SDK or later

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

建立包含 Razor UI 的類別庫Create a class library containing Razor UI

  • 從 Visual Studio 的 [檔案] 功能表中,選取 [新增] > [專案] 。From the Visual Studio File menu, select New > Project.
  • 選取 [ASP.NET Core Web 應用程式] 。Select ASP.NET Core Web Application.
  • 命名程式庫 (例如,"RazorClassLib") > [確定] 。Name the library (for example, "RazorClassLib") > OK. 若要避免與產生的檢視程式庫發生檔案名稱衝突,程式庫名稱結尾請務必不要使用 .ViewsTo avoid a file name collision with the generated view library, ensure the library name doesn't end in .Views.
  • 確認已選取 ASP.NET Core 2.1 或更新版本。Verify ASP.NET Core 2.1 or later is selected.
  • 選取 [Razor 類別庫] > [確定] 。Select Razor Class Library > OK.

RCL 具有下列專案檔:An RCL has the following project file:

<Project Sdk="Microsoft.NET.Sdk.Razor">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.2" />
  </ItemGroup>

</Project>

新增 Razor 檔案至 RCL。Add Razor files to the RCL.

ASP.NET Core 範本假設 RCL 內容位於領域資料夾。The ASP.NET Core templates assume the RCL content is in the Areas folder. 請參閱RCL 網頁版面配置建立中的內容會公開 RCL~/Pages而非~/Areas/PagesSee RCL Pages layout to create an RCL that exposes content in ~/Pages rather than ~/Areas/Pages.

參考 RCL 內容Referencing RCL content

RCL 可以由下列各項參考:The RCL can be referenced by:

逐步解說:建立 RCL 專案,並使用從 Razor Pages 專案Walkthrough: Create an RCL project and use from a Razor Pages project

您可以下載完整專案並測試它,而不是建立它。You can download the complete project and test it rather than creating it. 下載範例包含額外的程式碼和連結,讓您輕鬆地測試專案。The sample download contains additional code and links that make the project easy to test. 您可以在此 GitHub 問題留下意見反應以及您對下載範例與逐步指示的評論。You can leave feedback in this GitHub issue with your comments on download samples versus step-by-step instructions.

測試下載應用程式Test the download app

如果您尚未下載已完成的應用程式,而是要建立逐步解說專案,請跳至下一節If you haven't downloaded the completed app and would rather create the walkthrough project, skip to the next section.

在 Visual Studio 中開啟 .sln 檔案。Open the .sln file in Visual Studio. 執行應用程式。Run the app.

遵循測試 WebApp1 中的指示執行。Follow the instructions in Test WebApp1

建立 RCLCreate an RCL

在本節中,會建立 RCL。In this section, an RCL is created. 會有 Razor 檔案新增至 RCL。Razor files are added to the RCL.

建立 RCL 專案:Create the RCL project:

  • 從 Visual Studio 的 [檔案] 功能表中,選取 [新增] > [專案] 。From the Visual Studio File menu, select New > Project.
  • 選取 [ASP.NET Core Web 應用程式] 。Select ASP.NET Core Web Application.
  • 將應用程式命名RazorUIClassLib > 確定Name the app RazorUIClassLib > OK.
  • 確認已選取 ASP.NET Core 2.1 或更新版本。Verify ASP.NET Core 2.1 or later is selected.
  • 選取 [Razor 類別庫] > [確定] 。Select Razor Class Library > OK.
  • 新增名為 RazorUIClassLib/Areas/MyFeature/Pages/Shared/_Message.cshtml 的 Razor 部分檢視檔。Add a Razor partial view file named RazorUIClassLib/Areas/MyFeature/Pages/Shared/_Message.cshtml.

加入專案中的 Razor 檔案和資料夾Add Razor files and folders to the project

  • RazorUIClassLib/Areas/MyFeature/Pages/Shared/_Message.cshtml 中的標記取代為下列程式碼:Replace the markup in RazorUIClassLib/Areas/MyFeature/Pages/Shared/_Message.cshtml with the following code:
<h3>_Message.cshtml partial view.</h3>

<p>RazorUIClassLib\Areas\MyFeature\Pages\Shared\_Message.cshtml</p>
  • RazorUIClassLib/Areas/MyFeature/Pages/Page1.cshtml 中的標記取代為下列程式碼:Replace the markup in RazorUIClassLib/Areas/MyFeature/Pages/Page1.cshtml with the following code:
@page
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h2>Hello from a Razor UI class library!</h2>
<p> From  RazorUIClassLib\Areas\MyFeature\Pages\Page1.cshtml</p>

<partial name="_Message" />

需要 @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 才能使用部分檢視 (<partial name="_Message" />)。@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers is required to use the partial view (<partial name="_Message" />). 您可以新增 _ViewImports.cshtml 檔案,而不要包含 @addTagHelper 指示詞。Rather than including the @addTagHelper directive, you can add a _ViewImports.cshtml file. 例如:For example:

dotnet new viewimports -o RazorUIClassLib/Areas/MyFeature/Pages

如需詳細資訊 _ViewImports.cshtml,請參閱匯入共用指示詞For more information on _ViewImports.cshtml, see Importing Shared Directives

  • 建置類別庫,以確認沒有任何編譯器錯誤:Build the class library to verify there are no compiler errors:
dotnet build RazorUIClassLib

建置輸出包含 RazorUIClassLib.dllRazorUIClassLib.Views.dllThe build output contains RazorUIClassLib.dll and RazorUIClassLib.Views.dll. RazorUIClassLib.Views.dll 包含已編譯的 Razor 內容。RazorUIClassLib.Views.dll contains the compiled Razor content.

從 Razor 頁面專案使用 Razor UI 程式庫Use the Razor UI library from a Razor Pages project

建立 Razor 頁面 Web 應用程式:Create the Razor Pages web app:

  • 在 [方案總管] 中,以滑鼠右鍵按一下解決方案 > [新增] > [新增專案] 。From Solution Explorer, right-click the solution > Add > New Project.

  • 選取 [ASP.NET Core Web 應用程式] 。Select ASP.NET Core Web Application.

  • 將應用程式命名為 WebApp1Name the app WebApp1.

  • 確認已選取 ASP.NET Core 2.1 或更新版本。Verify ASP.NET Core 2.1 or later is selected.

  • 選取 [Web 應用程式] > [確定] 。Select Web Application > OK.

  • 從 [方案總管] ,以滑鼠右鍵按一下 WebApp1,然後選取 [設定為啟始專案] 。From Solution Explorer, right-click on WebApp1 and select Set as StartUp Project.

  • 從方案總管 ,以滑鼠右鍵按一下 WebApp1,然後選取 [建置相依性] > [專案相依性] 。From Solution Explorer, right-click on WebApp1 and select Build Dependencies > Project Dependencies.

  • 核取 RazorUIClassLib 作為 WebApp1 的相依性。Check RazorUIClassLib as a dependency of WebApp1.

  • 從 [方案總管] ,以滑鼠右鍵按一下 WebApp1,然後選取 [新增] > [參考] 。From Solution Explorer, right-click on WebApp1 and select Add > Reference.

  • 在 [參考管理員] 對話方塊中,核取 RazorUIClassLib > [確定] 。In the Reference Manager dialog, check RazorUIClassLib > OK.

執行應用程式。Run the app.

測試 WebApp1Test WebApp1

確認 Razor UI 類別庫是使用中:Verify the Razor UI class library is in use:

  • 瀏覽至 /MyFeature/Page1Browse to /MyFeature/Page1.

覆寫檢視、部分檢視和頁面Override views, partial views, and pages

在 Web 應用程式和 RCL 中發現檢視、部分檢視,或是 Razor 頁面時,以 Web 應用程式中的 Razor 標記 ( .cshtml 檔案) 為優先。When a view, partial view, or Razor Page is found in both the web app and the RCL, the Razor markup (.cshtml file) in the web app takes precedence. 例如,新增WebApp1/Areas/MyFeature/Pages/Page1.cshtml WebApp1,以和 Page1 WebApp1 中的將會優先於 RCL 中的 Page1。For example, add WebApp1/Areas/MyFeature/Pages/Page1.cshtml to WebApp1, and Page1 in the WebApp1 will take precedence over Page1 in the RCL.

在下載範例中,將 WebApp1/Areas/MyFeature2 重新命名為 WebApp1/Areas/MyFeature 以測試優先順序。In the sample download, rename WebApp1/Areas/MyFeature2 to WebApp1/Areas/MyFeature to test precedence.

RazorUIClassLib/Areas/MyFeature/Pages/Shared/_Message.cshtml 部分檢視複製到 WebApp1/Areas/MyFeature/Pages/Shared/_Message.cshtmlCopy the RazorUIClassLib/Areas/MyFeature/Pages/Shared/_Message.cshtml partial view to WebApp1/Areas/MyFeature/Pages/Shared/_Message.cshtml. 更新標記來指示新的位置。Update the markup to indicate the new location. 建置並執行應用程式,以確認正在使用部分檢視的應用程式版本。Build and run the app to verify the app's version of the partial is being used.

RCL 網頁版面配置RCL Pages layout

參考 RCL 內容,就好像它是 web 應用程式的一部分資料夾中,建立 RCL 專案檔案結構如下:To reference RCL content as though it is part of the web app's Pages folder, create the RCL project with the following file structure:

  • RazorUIClassLib/頁面RazorUIClassLib/Pages
  • RazorUIClassLib/網頁/共用RazorUIClassLib/Pages/Shared

假設RazorUIClassLib/網頁/Shared包含兩個部分的檔案: _Header.cshtml_Footer.cshtmlSuppose RazorUIClassLib/Pages/Shared contains two partial files: _Header.cshtml and _Footer.cshtml. <partial>標記新增到 _Layout.cshtml檔案:The <partial> tags could be added to _Layout.cshtml file:

<body>
  <partial name="_Header">
  @RenderBody()
  <partial name="_Footer">
</body>

使用靜態資產建立 RCLCreate an RCL with static assets

RCL 可能需要的 RCL 使用的應用程式可以參考的附屬靜態資產。An RCL may require companion static assets that can be referenced by the consuming app of the RCL. ASP.NET Core 可讓您建立包含可供使用的應用程式靜態資產的 RCLs。ASP.NET Core allows creating RCLs that include static assets that are available to a consuming app.

若要納入隨附資產 RCL,建立wwwroot類別庫中的資料夾,並在該資料夾中包含任何必要的檔案。To include companion assets as part of an RCL, create a wwwroot folder in the class library and include any required files in that folder.

當封裝 RCL,所有附屬中的資產wwwroot資料夾會自動包含在封裝中,並且可供參考套件的應用程式。When packing an RCL, all companion assets in the wwwroot folder are included in the package automatically and are made available to apps referencing the package.

使用來自參考 RCL 內容Consume content from a referenced RCL

中包含的檔案wwwroot RCL 資料夾會公開使用的應用程式,在前置詞至_content/{LIBRARY NAME}/The files included in the wwwroot folder of the RCL are exposed to the consuming app under the prefix _content/{LIBRARY NAME}/. {LIBRARY NAME} 程式庫專案名稱轉換成小寫與期間 (.) 移除。{LIBRARY NAME} is the library project name converted to lowercase with periods (.) removed. 例如,名為媒體櫃Razor.Class.Lib靜態內容,在產生的路徑_content/razorclasslib/For example, a library named Razor.Class.Lib results in a path to static content at _content/razorclasslib/.

使用的應用程式參考與程式庫所提供的靜態資產<script><style><img>,以及其他的 HTML 標記。The consuming app references static assets provided by the library with <script>, <style>, <img>, and other HTML tags. 使用的應用程式必須擁有靜態檔案支援啟用。The consuming app must have static file support enabled.

多專案的開發流程Multi-project development flow

使用的應用程式執行時:When the consuming app runs:

  • RCL 留在原始資料夾中的資產。The assets in the RCL stay in their original folders. 資產不會移至使用的應用程式。The assets aren't moved to the consuming app.
  • RCL 中的任何變更wwwroot資料夾會反映在 使用的應用程式之後重建 RCL,而不需重建使用的應用程式。Any change within the RCL's wwwroot folder is reflected in the consuming app after the RCL is rebuilt and without rebuilding the consuming app.

建置 RCL 時,會產生資訊清單描述靜態 web 資產位置。When the RCL is built, a manifest is produced that describes the static web asset locations. 使用的應用程式會讀取在執行階段使用 從參考的專案和封裝資產的資訊清單。The consuming app reads the manifest at runtime to consume the assets from referenced projects and packages. 當新的資產新增至 RCL 時,您就必須重建 RCL 之前使用的應用程式可以存取新的資產更新其資訊清單。When a new asset is added to an RCL, the RCL must be rebuilt to update its manifest before a consuming app can access the new asset.

發行Publish

發行應用程式時,所有參考的專案和套件隨附資產會複製到wwwroot資料夾的已發佈的應用程式下_content/{LIBRARY NAME}/When the app is published, the companion assets from all referenced projects and packages are copied into the wwwroot folder of the published app under _content/{LIBRARY NAME}/.