I this artical i will explain how to save value in cookies and how to get those values when needed.
why we need this
I was developed a Web application in mvc where session time out create problems ,so to handle this satuation i use cookies.
without time waste let me explain how to do all this.
follow step
create class
public class ManageCookies
{
public void SetCookies(string EncodedCredentials)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["GlobalCookieName"] ??new HttpCookie("GlobalCookieName ");
cookie.Values["EncodedCredentials"] = EncodedCredentials;
cookie.Expires = DateTime.Now.AddDays(1);HttpContext.Current.Response.Cookies.Add(cookie);
}
public bool GetCookies()
{
try
{
if (HttpContext.Current.Request.Cookies["GlobalCookieName"] != null)
{
string EncodedCredentials = HttpContext.Current.Request.Cookies["GlobalCookieName"]["EncodedCredentials"].ToString();
string data = BusinessManager.Base64Decode(EncodedCredentials);
string[] credentials = data.Split(':');
string username = credentials[0].Trim();
string password = credentials[1].Trim();
return SetSession(username, password);
}
}
catch (Exception ex)
{return false;
}
return false;
}public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}private bool SetSession(string UserName,string Password)
{
myDB storeDb = new myDB ();//here you can make a request for DB
}
2 on session exoire im checkin if session expire then get use your cookies class to reset sesion
public class SessionExpireAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check your sessions here
if (HttpContext.Current.Session[SessionKeyItems.Profile] == null)
{
ManageCookies manageCookies = new ManageCookies();
if (manageCookies.GetCookies())
{
return;
}
filterContext.Result = new RedirectResult("~/Account/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}