我已经按照以下方式在Asp.Net Core 2.2中实现了身份验证:
public async Task<IActionResult> LoginAsync(string user, string password)
{
if (user == "admin" && password == "admin")
{
var claims = new[] { new Claim(ClaimTypes.Name, user),
new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity));
return RedirectToAction("Index", "Home");
{
else
{
return RedirectToAction("Login", "Users");
}
现在我需要进行注销操作。在Asp.Net MVC中,我曾使用FormsAuthentication.SignOut()来实现此操作... 现在我需要知道在Asp.Net Core 2.2中正确的做法。
我尝试创建以下Logout action:
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index","Home");
}
我在我的导航栏中使用了以下代码:
@if (User.Identity.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.Name + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li class="nav-item">
<form class="form-inline" asp-area="Identity" asp-page="/Users/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
根据文档的指示:
虽然正确显示了“登出”按钮,但按下该按钮似乎没有触发我的操作,用户也没有成功退出登录。