在默认的Razor Pages项目模板中,启用Razor Pages的Startup.cs中的部分代码是对Configure()的端点配置部分中的MapRazorPages()的调用:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
[Rick Anderson和Ryan Nowak在出色的Introduction to Razor Pages in ASP.NET Core文章中证实了此呼叫的必要性。
虽然Blazor是一种不同的UI技术,但Blazor项目也能够公开Razor Pages端点。例如,包含ASP.NET身份验证的Blazor项目将“登录”和“注销”页面公开为“剃刀页面”。
但是,公开Razor页面的Blazor项目中的端点初始化似乎不涉及对MapRazorPages()的调用。如果使用默认的Blazor模板通过单个用户帐户身份验证来创建新项目,然后在ASP.NET Identity使用的所有Razor页面中使用脚手架,则端点初始化看起来像这样:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
生成的应用程序能够正确地将请求路由到Razor Pages端点,例如Login.cshtml和LogOut.cshtml。没有调用MapRazorPages()怎么办?
首先看一下下面的代码片段(注意两行中的突出显示的行)
/// <summary>
/// Adds endpoints for Razor Pages to the <see cref="IEndpointRouteBuilder"/>.
/// </summary>
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/>.</param>
/// <returns>An <see cref="PageActionEndpointConventionBuilder"/> for endpoints associated with Razor Pages.</returns>
public static PageActionEndpointConventionBuilder MapRazorPages(this IEndpointRouteBuilder endpoints)
{
if (endpoints == null)
{
throw new ArgumentNullException(nameof(endpoints));
}
EnsureRazorPagesServices(endpoints); //<-- NOTE THIS
return GetOrCreateDataSource(endpoints).DefaultBuilder;
}
MapFallbackToPage
它们都调用配置功能以处理剃刀页面请求的核心功能。