zoukankan      html  css  js  c++  java
  • C#WebApi Session存储验证码过程中发现的问题

    C#WebApi Session存储验证码过程中发现的问题

    webapi开发的过程中,领导要求验证码需要后台实现然后网页前端和app展示。无奈只能硬着头皮上。大概过程就是后台自动生成一个4位或者多位随机字符串,存入HttpContext.Current.Session中,然后前端网页或者app登陆时传给后端,后端通过对比HttpContext.Current.Session与传过来的值来对比验证码是否正确,传给网页前端或app,然后由前端或app控制展现的格式。在实现的过程中。网页没有发现问题,但是app却出现一个令人头疼的问题。每次app请求验证码之后,HttpContext.Current.Session.SessionID的值都会变更,这是我不想看到的。因为SessionId的值一旦改变,Session中的验证码就会丢失。进过多次联调,终于发现了其中的问题。下面是我个人的理解:每次网页前端或者app请求接口的时候,后端都会检查SessionID是否为空,如果为空,就会默认生成一个SessionID,然后返回Response的时候,会默认把sessionID的值存到一个cookie中并且返回请求方,这个默认生成的cookie的过期时间是返回时间之后的20分钟,但是在我的实现中,cookie的过期时间总会比现在的北京时间晚8个小时,也就是UTC时间,因为网页前端并没有判断cookie 的逻辑,所以网页前端请求验证码的时候,并不会出现什么问题,但是app请求的时候会判断cookie的过期时间,所以每次请求过后,cookie都是过期 的,所以每次请求都是新的SessionID,这就需要后端返回的时候,不使用自动生成的cookie,返回Response之前,生成自己的cookie,并且把SessionID存进去,并且把Cookie过期时间设置成正确的时间。实现思路大概就是这样,说的不好或者不清楚的还望大佬们多多包涵,有想法的可以多多交流,下面附上代码:

    实现验证生成及存储的代码:

     [HttpGet]
           public IHttpActionResult GetVerificationCode(int length=4)
          {
               if (CodeCreater.CreateCode(length,out string code))
              {
                   HttpContext.Current.Session.Add("VerificationCode", code);
                   
                   HttpCookie sessionCookie = new HttpCookie("ASP.NET_SessionId")
                  {
                       Value = HttpContext.Current.Session.SessionID,
                       Expires = DateTime.Now.AddHours(8).AddMinutes(30)
                  };
                   HttpContext.Current.Response.Cookies.Add(sessionCookie);

                   return Json(new { result = true, data = code });
              }
               else
              {
                   return Json(new { result = false, msg = "出现错误" });
              }
          }

    检验验证码是否正确的代码:

     if (userModel.VerificationCode == null)
                  {
                       return Json(new { result = false, msg = "验证码不能为空" });
                  }
                   var test = HttpContext.Current.Session["VerificationCode"].ToString();
                   if (userModel.VerificationCode.ToUpper() != HttpContext.Current.Session["VerificationCode"].ToString().ToUpper())
                  {
                       return Json(new { result = false, msg = "验证码不正确" });
                  }

     

  • 相关阅读:
    purple-class2-默认选项切换
    purple-accessData
    “/wechat”应用程序中的服务器错误。
    GDI+ 中发生一般性错误。
    ylbtech-Unitity-CS:Indexers
    ylbtech-Unitity-CS:Hello world
    ylbtech-Unitity-CS:Generics
    ylbtech-Unitity-CS:Delegates
    ZooKeeper目录
    Zookeeper常用命令 (转)
  • 原文地址:https://www.cnblogs.com/liangbin-2019-03-30/p/11313650.html
Copyright © 2011-2022 走看看