登录视图组件

默认项目模板创建一个部分视图 _LoginPartial.cshtml ,其中包含一些用于查明用户是否已登录并找出其用户名的逻辑。

由于视图组件可能更适合(因为涉及逻辑,甚至注入了 2 个服务),以下示例显示如何将 LoginPartial 转换为视图组件。

查看组件类

public class LoginViewComponent : ViewComponent
{
    private readonly SignInManager<ApplicationUser> signInManager;
    private readonly UserManager<ApplicationUser> userManager;

    public LoginViewComponent(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager)
    {
        this.signInManager = signInManager;
        this.userManager = userManager;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        if (signInManager.IsSignedIn(this.User as ClaimsPrincipal))
        {                
            return View("SignedIn", await userManager.GetUserAsync(this.User as ClaimsPrincipal));
        }
        return View("SignedOut");
    }
}

SignedIn 视图(在〜/ Views / Shared / Components / Login / SignedIn.cshtml 中)

@model WebApplication1.Models.ApplicationUser

<form asp-area="" asp-controller="Account" asp-action="LogOff" method="post" id="logoutForm" class="navbar-right">
    <ul class="nav navbar-nav navbar-right">
        <li>
            <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @Model.UserName!</a>
        </li>
        <li>
            <button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
        </li>
    </ul>
</form>

SignedOut 视图(在〜/ Views / Shared / Components / Login / SignedOut.cshtml 中)

<ul class="nav navbar-nav navbar-right">
    <li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
    <li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>

_Layout.cshtml 调用 ****

@await Component.InvokeAsync("Login")