Я создаю cookie со следующими строками:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Теперь, Как сделать это персистентным?
Поскольку, если я посещаю ту же страницу снова после закрытия браузера, я не могу вернуть его.
Вот как это можно сделать.
Запись постоянного файла cookie.
//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");
//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());
//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);
//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);
Чтение постоянного файла cookie.
//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
//No cookie found or cookie expired.
//Handle the situation here, Redirect the user or simply return;
}
//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
string userId = myCookie.Values["userid"].ToString();
//Yes userId is found. Mission accomplished.
}
FWIW: будьте очень осторожны, сохраняя что-то вроде идентификатора пользователя в файле cookie в незашифрованном виде. Это делает ваш сайт очень подверженным заражению cookie-файлами, когда пользователи могут легко выдать себя за другого пользователя. Если вы рассматриваете что-то подобное, я настоятельно рекомендую напрямую использовать cookie проверки подлинности форм.
bool persist = true;
var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);
cookie.Expires = DateTime.Now.AddMonths(3);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var userData = "store any string values you want inside the ticket
extra than user id that will be encrypted"
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
cookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(cookie);
Затем вы можете прочитать это в любое время на странице ASP.NET, выполнив
string userId = null;
if (this.Context.User.Identity.IsAuthenticated)
{
userId = this.Context.User.Identity.Name;
}
Вам нужно добавить это как последнюю строку ...
HttpContext.Current.Response.Cookies.Add(userid);
Когда вам нужно прочитать значение cookie, вы должны использовать метод, аналогичный это:
string cookieUserID= String.Empty;
try
{
if (HttpContext.Current.Request.Cookies["userid"] != null)
{
cookieUserID = HttpContext.Current.Request.Cookies["userid"];
}
}
catch (Exception ex)
{
//handle error
}
return cookieUserID;