Session的使用过程中应注意的一个小问题

  在学习AllEmpty大神的从零开始编写自己的C#框架系列文章中,发现的问题:在验证码的缓存Session["vcode"]的赋值时,发现Session["vcode"]的值一直为null。

  发现原来是在调用验证码生成类给Session["vcode"]赋值时,这个Session["vcode"]还没有创建,所以无法赋值。

1  //生成验证码
2 imgCaptcha.ImageUrl = "Application/Vcode.ashx?t=" + DateTime.Now.Ticks;

Vcode.ashx中,验证码生成并向Session["vcode"]赋值:

 1 VerificationCode vcode = new VerificationCode
 2             {
 3                 CountCode = 5,
 4                 ImageHeight = 32,
 5                 ImageWidth = 100,
 6                 NoiseLine = 50,
 7                 NoisePoint = 80,
 8                 FontSize = 24
 9             };
10             //生成验证码
11             vcode.GetCaptcha();
12             //向Session["vcode"]中赋值
13             HttpContext.Current.Session["vcode"] = vcode.Code;
14             string code = HttpContext.Current.Session["vcode"].ToString();//调试用,会报【未将对象引用设置到对象的实例】错误

解决办法是在调用Vcode.ashx之前,声明Session["vcode"]

1                 //声明Session["vcode"],并赋空值
2                 Session["vcode"] = string.Empty;
3                 //生成验证码
4                 imgCaptcha.ImageUrl = "Application/Vcode.ashx?t=" + DateTime.Now.Ticks;

 

转载于:https://www.cnblogs.com/Amyn/p/4276344.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值