登入檢視元件

預設專案模板建立一個部分檢視 _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")