c# - 使用 Asp.Net Core Cookie 身份验证的注销操作
问题描述
我在 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 Task<IActionResult> 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>
}
遵循本文档中的说明
这正确显示了注销按钮,但按下按钮似乎不会触发我的操作,并且用户没有注销。
解决方案
原来我只是在我的视图中犯了一个错误。我在表格中调用了错误的操作。
使用 (Html.BeginForm("
LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
应该是Html.BeginForm("Logout","Users", ...)
此外,我的表单正在发送一个 Post 请求,所以我的操作必须用 装饰[HttpPost]
,如下所示:
[HttpPost]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index","Home");
}
推荐阅读
- java - Spring - Spark:jar/依赖项之间的冲突
- c# - 如何在 Headless 模式下运行我的 Selenium 项目?
- linux - Docker 卷挂载为空
- php - 拉拉维尔 | 大量数据的特殊验证
- sql - 过滤条件的性能输出
- reactjs - React 新手,无法让 ReactDOM 渲染 javascript 组件
- perl - 如何在 Windows 10 上重新启动我的 Perl 脚本
- angular - 如何获得与我的 Table 对象的列名称相对应的正确数量的 formsControl,而无需努力编写
- python - 如何创建一系列单词以作为超参数进行迭代?
- azure-devops - Azure DevOps - 对“迭代”字段执行操作的新工作项规则