问题:在使用Cookie传递中文时,后台读取Cookies时出现乱码问题!!!
使用场景:在ASP.NET MVC 中写入Cookie值,在ASP.NET MVC Core读取Cookie值!!
解决方法:
一、 在asp.net mvc中写入Cookie值
1 HttpCookie cook = new HttpCookie("UINFO"); 2 cook.Expires = DateTime.Now.AddDays(7); 3 cook.Domain = ".ceshi.com"; 4 cook.Value = System.Web.HttpUtility.UrlEncode("中文会乱码"); 5 Response.Cookies.Add(cook);
二、在asp.net mvc core中读取Cookie值
1、封装获取Cookie方法
/// <summary> /// 获取cookies /// </summary> /// <param name="context">请求上下文</param> /// <param name="key">key值</param> /// <returns></returns> public static string GetCookies(HttpContext context, string key) { context.Request.Cookies.TryGetValue(key, out string value); if (string.IsNullOrEmpty(value)) value = string.Empty; return value; }
2、通过cookie名获取Cookie;
1 string pccookie = CookieHelper.GetCookies(context, "UINFO"); 2 string deCookie = System.Web.HttpUtility.UrlDecode(pccookie);
以上方法可以完美解决Cookie传递中文问题!!!