前言
Razor Class Library 的用途是封装 Razor views, pages, controllers, page models, Razor components, View components, and data models, 到一个独立的 Library, 然后 share with multiple projects.
以前介绍 Identity – Introduction & Scaffold 的时候就有提到过, ASP.NET Core 封装了一些 Login, User Management 的 Pages, 方便我们快速启动 Identity.
官网的例子更多是用在 Blozor + Razor components. 但是我没有用 Blozor 和 Razor components. 我只用 Razor pages 和 View component.
所以这篇给的例子是 Razor Pages + View Component.
参考
Docs – Create reusable UI using the Razor class library project in ASP.NET Core
Docs – Consume ASP.NET Core Razor components from a Razor class library (RCL)
创建项目
1 个 web app, 一个 library.
mkdir TestRazorClassLibrary cd TestRazorClassLibrary dotnet new razorclasslib -o MyRazorLibrary --support-pages-and-views dotnet new webapp -o MyWebApp dotnet add MyWebApp reference MyRazorLibrary
注意: new razorclasslib 需要添加 --support-pages-and-views, 因为我要 share 的是 View Component.
最后一行是添加 reference, 因为 library 没有发布到 nuget.
创建 View Component in Library
用 VS Code 打开 TestRazorClassLibrary folder
把 build-in 创建的 Area 洗掉, 创建 component folder
HelloWorldViewComponent.cs
using Microsoft.AspNetCore.Mvc; namespace MyRazorLibrary; public class HelloWorldViewComponent : ViewComponent { public IViewComponentResult Invoke() { return View("~/Component/HelloWorld/Index.cshtml"); } }
Index.cshtml
<h1>Hello World</h1>
调用 View Component in Web App
Index.cshtml
@page @model IndexModel @addTagHelper *, MyRazorLibrary @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> <vc:hello-world></vc:hello-world>
运行
dotnet watch run --project MyWebApp