添加cookie 汉字需UrlEncode
var cookieValue = string.Format("{0}&{1}&{2}", user.Id, HttpUtility.UrlEncode(user.CompanyName), user.RoleId);
HttpCookie Cookie = new HttpCookie(Constant.Manager, cookieValue);
Cookie.Expires = DateTime.Now.AddHours(2);
Response.Cookies.Add(Cookie);
删除cookie
Response.Cookies[Constant.Manager].Expires = DateTime.Now.AddDays(-1);
cookie取值
var cookie = Request.Cookies[Constant.Manager];
if (cookie == null)
{
return View("login");
}
ViewBag.CompanyName = HttpUtility.UrlDecode(cookie.Value.Split('&')[1]);
浏览器js设置cookie
function setCookie(name, value) {
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
}
function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return unescape(arr[2]);
else
return "";
}