Reputation: 1171
//Interface--Injecting into controller
public interface IContext
{
HttpRequestBase Request { get; }
HttpResponseBase Response { get; }
}
//Implementation
public class Context : IContext
{
public HttpRequestBase Request { get { return new HttpRequestWrapper(HttpContext.Current.Request); } }
public HttpResponseBase Response { get { return new HttpResponseWrapper(HttpContext.Current.Response); } }
}
//Setting Cookie on login. SetCookie(_context, login);
public void SetCookie(IContext context, Login login)
{
var loginDetails = new JavaScriptSerializer().Serialize(login);
var cokie = new HttpCookie("login", login);
context.Response.Cookies.Add(cokie);
}
//Trying to Logout.
public ActionResult Logout()
{
foreach (var key in _context.Request.Cookies.AllKeys)
{
try
{
_context.Response.Cookies.Remove(key); //this didn't work
//tried this even this is not working
var login = new Login {Identity = "", LogIn = false};
_login.SetCookie(_context, login);
}
catch (Exception e)
{
}
}
_context.Response.Cookies.Clear(); //this didn't work either
return RedirectToAction("Index", "Login");
}
On Login Index when I check the current login cookie value it always has the value of the logged in user is just not getting set to null or empty. I suspect there is something wrong in the Implementation of the IContext. Should there be a setter on it? Not sure..
Also Tried:
var cokie = context.Request.Cookies["login"];
cokie.Expires = DateTime.Now.AddDays(-2);
cokie.Value = null;
context.Response.Cookies.Add(cokie);
Upvotes: 1
Views: 8143
Reputation: 285
You can use the below code if you are using forms authentication. It will clear all the required cookies
FormsAuthentication.SignOut();
Session.Abandon();
Alternatively you can use
Session.Abandon();
Response.Cookies.Clear();
or
YourCookies.Expires = DateTime.Now.AddDays(-1d);
For more information please visit
Upvotes: 3
Reputation: 815
If to log user in you use
SignInManager.PasswordSignInAsync(...)
you can try
AuthenticationManager.SignOut();
instead of
_context.Response.Cookies.Clear();
Upvotes: 0