前后端分离项目,配置问题导致后端session丢失问题
今天遇到一个巨坑,后端写了获取验证码接口,以及验证验证码接口
获取验证码接口:
/// <summary> /// 获取验证码 /// </summary> /// <returns></returns> [AllowAnonymous] public FileResult VerificationCode() { return File(this.CreateCheckCodeImage(GenerateCheckCode()).ToArray(), "image/Gif"); }
private string GenerateCheckCode() { int number; char code; string checkCode = String.Empty; System.Random random = new Random(); for (int i = 0; i < 5; i++) { number = random.Next(); if (number % 2 == 0) code = (char)('0' + (char)(number % 10)); else code = (char)('A' + (char)(number % 26)); if (code == '0') code = 'M'; checkCode += code.ToString(); } Session["CheckCode"] = checkCode; return checkCode; } private MemoryStream CreateCheckCodeImage(string checkCode) { if (checkCode == null || checkCode.Trim() == String.Empty) return null; System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 26.5)), 30); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的背景噪音线 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.ForestGreen), x1, y1, x2, y2); } Font font = new System.Drawing.Font("Tahoma", 20, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.ForestGreen, Color.DarkRed, 1.2f, true); g.DrawString(checkCode, font, brush, -5, -5); //画图片的前景噪音点 for (int i = 0; i < 80; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); return ms; } finally { g.Dispose(); image.Dispose(); } }
验证验证码接口:
/// <summary> /// 验证 验证码是否正确 /// </summary> /// <param name="Code"></param> /// <returns></returns> private bool CheckCode(string Code) { if (HttpContext.Current.Session["CheckCode"] == null) { HttpContext.Current.Session.Remove("CheckCode"); return false; } if (HttpContext.Current.Session["CheckCode"].ToString().Equals(Code, StringComparison.CurrentCultureIgnoreCase) == false) { HttpContext.Current.Session.Remove("CheckCode"); return false; } HttpContext.Current.Session.Remove("CheckCode"); return true; }
使用的测试工具是APIpost,经过测试两个接口通过session存取验证码没有问题,都是可以调通的,但是部署项目的时候因为是前后端分离项目,需要配置跨域,跨域可以选择前端配置以及后端配置。
这里我使用的是后端配置
配置完成之后,前端调用验证码接口一直验证失败,经过日志输出,发现是session丢失问题,到这里有两个解决方案
方案一:更改配置信息,以及前端配置相关信息
跨域注意
1.前端ajax访问时要加上“xhrFields: {withCredentials: true}” ,实现session可以传递;
2.配置拦截器,response.setHeader(“Access-Control-Allow-Origin”, “*”),实现跨域访问问题;
3.配置拦截器,response.addHeader(“Access-Control-Allow-Credentials”, “true”),实现session传值问题;*
4.配置拦截器,如果配置了Access-Control-Allow-Credentials=true,则跨域拦截Access-Control-Allow-Origin 必须是指定的url,response.setHeader(“Access-Control-Allow-Origin”, url);
方案二:使用其他技术实现验证验证码,这里我使用的是缓存
CacheHelp.Set(
key: "验证码缓存",
value: checkCode,
Seconds: 7200 //缓存时长,单位“秒”
);
我这里给出一个缓存帮助类
public class CacheHelp { /// <summary> /// 缓存指定对象,设置缓存 /// </summary> /// <param name="key">缓存的key</param> /// <param name="value">缓存的值</param> /// <param name="Seconds">设置缓存时间;单位:秒</param> /// <returns></returns> public static bool Set(string key, object value, double Seconds) { return Set(key, value, null, DateTime.Now.AddSeconds(Seconds), Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } /// <summary> /// 缓存指定对象,设置缓存 /// </summary> public static bool Set(string key, object value, string path) { try { var cacheDependency = new CacheDependency(path); return Set(key, value, cacheDependency); } catch { return false; } } /// <summary> /// 缓存指定对象,设置缓存 /// </summary> public static bool Set(string key, object value, CacheDependency cacheDependency) { return Set(key, value, cacheDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } /// <summary> /// 缓存指定对象,设置缓存 /// </summary> public static bool Set(string key, object value, double seconds, bool isAbsulute) { return Set(key, value, null, (isAbsulute ? DateTime.Now.AddSeconds(seconds) : Cache.NoAbsoluteExpiration), (isAbsulute ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(seconds)), CacheItemPriority.Default, null); } /// <summary> /// 获取缓存对象 /// </summary> public static object Get(string key) { return GetPrivate(key); } /// <summary> /// 判断缓存中是否含有缓存该键 /// </summary> public static bool Exists(string key) { return (GetPrivate(key) != null); } /// <summary> /// 移除缓存对象 /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool Remove(string key) { if (string.IsNullOrEmpty(key)) { return false; } HttpRuntime.Cache.Remove(key); return true; } /// <summary> /// 移除所有缓存 /// </summary> /// <returns></returns> public static bool RemoveAll() { IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator(); while (iDictionaryEnumerator.MoveNext()) { HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key)); } return true; } /// <summary> /// 尝试获取缓存,不存在则执行匿名委托 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="func"></param> /// <param name="Seconds">设置缓存时间;单位:秒</param> /// <returns></returns> public static T TryGet<T>(string key, Func<T> func, double Seconds) { if (Exists(key)) return (T)Get(key); var result = func.Invoke(); Set(key, result, Seconds); return result; } /// <summary> /// 设置缓存 /// </summary> public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime dateTime, TimeSpan timeSpan, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback) { if (string.IsNullOrEmpty(key) || value == null) { return false; } HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority, cacheItemRemovedCallback); return true; } /// <summary> /// 获取缓存 /// </summary> private static object GetPrivate(string key) { return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key); } }
希望小伙伴们遇到这种问题时候能够有一个解决思路!!!!!