【问题标题】:C# Session not saved from HTTPHandlerC# 会话未从 HTTPHandler 保存
【发布时间】:2010-12-06 08:16:57
【问题描述】:

我有一个 HTTPHandler,只要请求 captcha.ashx 页面,它就会为用户生成一个 Captcha 图像。它的代码很简单:

        CaptchaHandler handler = new CaptchaHandler();
        Random random = new Random();
        string[] fonts = new string[4] { "Arial", "Verdana", "Georgia", "Century Schoolbook" };
        string code = Guid.NewGuid().ToString().Substring(0, 5);
        context.Session.Add("Captcha", code);

        Bitmap imageFile = handler.GenerateImage(code, 100, 70, fonts[random.Next(0,4)]);
        MemoryStream ms = new MemoryStream();
        imageFile.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        byte[] buffer = ms.ToArray();

        context.Response.ClearContent();
        context.Response.ContentType = "image/png";
        context.Response.BinaryWrite(buffer);
        context.Response.Flush();

然后在我的常规网站上,我得到了以下信息:

...
<img id="securityCode" src="captcha.ashx" alt="" /><br />
<a href="javascript:void(0);" onclick="javascript:refreshCode();">Refresh</a>
...

这很完美,只要请求 captcha.ashx 页面,就会生成图像并将其发送回用户。我的问题是 HTTPHandler 不保存会话? 我试图从正常页面取回会话,但我只有一个异常说它不存在,所以我打开 Trace 以查看哪些会话处于活动状态并且它没有列出 HTTPHandler 创建的会话(验证码)。

HTTPHandler 使用 IReadOnlySessionState 与会话进行交互。 HTTPHandler 是否只有读取权限,因此不存储会话?

【问题讨论】:

    标签: c# session httphandler captcha


    【解决方案1】:

    尝试从命名空间实现 IRequiresSessionState 接口。

    查看此链接:http://anuraj.wordpress.com/2009/09/15/how-to-use-session-objects-in-an-httphandler/

    【讨论】:

    • +1 - 搜索旧问题很少会浪费时间。这也为我解决了完全相同的问题 - 谢谢。
    【解决方案2】:

    您的 Handler 需要实现 IRequiresSessionState。

    public class CaptchaHandler : IHttpHandler, IRequiresSessionState
    {
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-01
      • 2012-09-06
      • 2012-11-29
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      相关资源
      最近更新 更多