I have got a standard AccountController class of ASP.NET MVC5 project.
When I try to log out user I am facing an error coz HttpContext
is null
. (I mean here HttpContext
.GetOwinContext().Authentication is null)
So I cannot get how we can logout user when session ends...
In global.asax I have got this
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 has
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")
});
}
I tried all this out:
System.Web.HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
FormsAuthentication.SignOut();
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
Request.GetOwinContext().Authentication.SignOut();
Request.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
but finally this solved my problem:
HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty),null);
Check
Assuming that you are using ApplicationCookie to store your login information.
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With