【发布时间】:2019-05-14 03:00:56
【问题描述】:
我已经像这样在 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>
}
遵循此documentaion的指示
这正确显示了注销按钮,但按下按钮似乎不会触发我的操作,并且用户没有注销。
【问题讨论】:
-
您好!欢迎来到stackoverflow。到目前为止你尝试了什么?文档对此有何评论?
-
@vasily.sib 我尝试使用 HttpContext.SignOutAsync() 进行注销操作,然后继续制作带有 asp-page="Users/Logout" 标记和内部提交按钮的表单,但是点击按钮后,什么也没有发生……我的按钮似乎没有触发我的动作。
-
那么您应该编辑您的问题以显示这一点。向我们展示您的
Logout操作(以及您应用到它的所有属性)以及用于触发该操作的表单 -
你试过调试吗?你真的打了你的
Logout行动吗?如果您在浏览器中打开开发者控制台,点击该按钮会收到来自服务器的什么响应? -
毕竟我没有采取行动......犯了愚蠢的错误。感谢您的帮助瓦西里。
标签: c# asp.net asp.net-core