我已经在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中执行此操作的正确方法
我尝试做的是这样的注销操作:
public async void Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index","Home");
}
并在我的NavBar中使用以下代码:
@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>
}
遵循此documentaion
中的说明这可以正确显示“注销”按钮,但是按该按钮似乎不会触发我的操作,并且用户也没有注销。
答案 0 :(得分:0)
原来,我只是在View中犯了一个错误。我在表单中称呼错误的动作。
使用(Html.BeginForm(“
注销”,“帐户”,FormMethod.Post,新的{id =“ logoutForm”,@class =“ navbar-right “}))
应该已经Html.BeginForm("Logout","Users, ...)
此外,我的表单正在发送一个Post请求,因此我的动作必须用[HttpPost]
装饰,如下所示:
[HttpPost]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index","Home");
}