asp-controller 和 asp-action 在 ASP.NET Core 3.1 Razor Pages 应用程序中不起作用

asp-controller and asp-action not working in ASP.NET Core 3.1 Razor Pages app

我有一个 ASP.NET Core 3.1 Razor Pages 应用程序,它允许用户登录和注销。

要注销,我有以下控制器:

public sealed class AccountController : Controller
{
    [Route("/Logout")]
    public async Task<IActionResult> LogoutAsync()
    {
        await this.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

        return this.RedirectToPage(ApplicationConstants.IndexPage);
    }
}

_Layout.cshtml 文件中我有以下内容:

<a class="nav-link" asp-controller="Account" asp-action="LogoutAsync"><i class="fa fa-sign-out fa-lg" aria-hidden="true"></i></a>

_Layout.cshtml 的父目录中的 _ViewImports.cshtml 文件中,我有以下内容:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Startup.cs 文件中,我添加了以下内容:

public void ConfigureServices(IServiceCollection services)
{
    // stuff

    services.AddControllers();

    services.AddRazorPages()
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.AuthorizePage("/Page1");
            options.Conventions.AuthorizePage("/Page2");
        });

    // more stuff
}

public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // stuff

    app.UseAuthentication();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
}

Visual Studio 似乎对这个设置很满意,并将 asp-controllerasp-action 识别为 ASP.NET 核心标签助手。

但是,当我 运行 应用程序时,link 呈现如下(注意空的 href):

<a class="nav-link" href=""><i class="fa fa-sign-out fa-lg" aria-hidden="true"></i></a>

我错过了什么?

备注:

据我所知,如果想让a标签生成herf,应该在Configure方法中设置路由模板。

更多详情,您可以参考以下代码:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/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?}");

        endpoints.MapRazorPages();
    });
}

结果:

看起来这是 ASP.NET Core 3.0 中引入的已知且有意的行为。

如果Action Method有Async后缀,将被忽略;因此,asp-action 不会将 LogoutAsync 视为有效的操作。

参考 this documentation about migrating to ASP.NET Core 3.0 from 2.2 and this GitHub 问题。