0

当我使用此控制器注销时:

public class LogOffController : Controller
{
    public ActionResult Index()
    {
        FormsAuthentication.SignOut();
        return View();
    }
}

呈现的页面不知道我已注销,并且在剃须刀页面的一部分中我显示用户:

@if (Request.IsAuthenticated)
{
  <text>Welcome <strong>@Profile.GetPropertyValue("FullName")</strong> 
  @if (User.IsInRole("Administrator"))
  {
     @Html.ActionLink("(Administrator)", "Index", "Administration")
  } 
  [ @Html.ActionLink("Log Off", "Index", "LogOff") ]</text>
}
else
{
  @Html.ActionLink("Login", "Index", "Login")
}

这仍然显示用户名和管理员角色,就像他们仍然登录一样。我导航到的下一页是正确的。

4

3 回答 3

2

Dave Zych 方法是一种更喜欢的方法。但是,如果您想像原始问题一样显示 LogOff View,您可以将 null 插入到当前线程的主体对象中。

public class LogOffController : Controller
{
    public ActionResult Index()
    {
        FormsAuthentication.SignOut();

        HttpContext.User = null;
        Thread.CurrentPrincipal = null;

        return View();
    }
}
于 2013-09-05T14:48:08.847 回答
1

而不是返回一个视图,使用RedirectToActionor RedirectToRoute

public class LogOffController : Controller
{
    public ActionResult Index()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "MyController");
    }
}
于 2013-09-05T14:25:27.420 回答
0

这是因为HttpContext.User在 ASP.NET 管道从身份验证 cookie 中读取值时设置。当你这样做时FormsAuthentication.SignOut();- 你只是告诉浏览器删除身份验证 cookie,但它对 .NET 当前用户一无所知。为了解决它,您有两种选择:

  • 将用户重定向到其他页面,以便您的请求再次通过管道,并且 .NET 知道用户是否已通过身份验证。
  • 手动注销用户:

    var currentUser = new GenericPrincipal(new GenericIdentity(string.Empty), null);
    HttpContext.User = currentUser;
    Thread.CurrentPrincipal = currentUser;
    

    请注意,您不应指定null为当前用户,因为在视图中您可能会遇到调用某些属性的情况User,例如User.Identity.IsAuthenticated

于 2014-11-12T16:04:40.023 回答