我有一个标准的AccountController类的ASP.NET MVC5项目。 当我尝试注销用户时,我遇到了错误,因为HttpContext
是null
。 (我的意思是HttpContext
.GetOwinContext()认证为null)如何在OWIN ASP.NET MVC5中注销用户
所以我不能让会话结束时,我们如何注销用户...
在Global.asax的我有这
protected void Session_Start(object sender, EventArgs e)
{
Session.Timeout = 3;
}
protected void Session_End(object sender, EventArgs e)
{
try
{
var accountController = new AccountController();
accountController.SignOut();
}
catch (Exception)
{
}
}
的AccountController
public void SignOut()
{
// Even if I do It does not help coz HttpContext is NULL
_authnManager = HttpContext.GetOwinContext().Authentication;
AuthenticationManager.SignOut();
}
private IAuthenticationManager _authnManager; // Add this private variable
public IAuthenticationManager AuthenticationManager // Modified this from private to public and add the setter
{
get
{
if (_authnManager == null)
_authnManager = HttpContext.GetOwinContext().Authentication;
return _authnManager;
}
set { _authnManager = value; }
}
Startup.Auth.cs有
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
ExpireTimeSpan = TimeSpan.FromMinutes(3),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
是的,我同意。我们默认有这种方法,但我想强制注销用户并将其重定向到登录页面。所以我需要解决方案来与OWIN做到这一点。无论如何感谢您的意见! – 2014-10-03 17:05:00
@ClarkKent这个解决方案确实可以和OWIN做到,我编辑了答案来解释它是如何做到的。请参阅待处理的修改。米兰解释了为什么它会在您注销用户之前抛出错误。 – Termato 2014-10-03 17:06:55
那么...... Ijust在'Session_End'中评论了代码,我面临着应用程序的奇怪行为。我把SessionTimeout 1分钟。当我登录并且什么都不做时,它工作正常。所以1分钟后,当我刷新页面时,它会注销并重定向到LOGIN页面。但是如果在2-3分钟内。我正在浏览网站,它不工作。 :) – 2014-10-03 17:24:56