如何在ASP.NET MVC中访问控制器之外的HttpContext?

Art*_*510 18 asp.net asp.net-mvc

具体来说,是Session变量.我的ASP.NET MVC项目中有一个.ashx,它将一些图像数据显示给用户,我需要能够访问我在会话中存储的对象.从控制器我可以很好地拉动对象,但在我的ashx页面中,context.Session为null.有什么想法吗?谢谢!

这是我正在尝试做的一个例子... context.Session总是返回null.

  private byte[] getIconData(string icon)
    {
        //returns the icon file
        HttpContext context = HttpContext.Current;

        byte[] buffer = null;

        //get icon data
        if ( context.Session["tokens"] != null)
        {
            //do some stuff to get icon data
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ala*_*aor 23

您必须在代码中导入System.Web程序集,然后您可以执行以下操作:

HttpContext context = HttpContext.Current;

return (User)context.Session["User"];
Run Code Online (Sandbox Code Playgroud)

编辑:

伙计,我在这里做了一些测试,它适用于我,尝试这样的事情:

创建一个帮助器类来封装你获取会话变量的东西,它必须导入System.Web程序集:

public class TextService
    {
        public static string Message { 
            get 
            { 
                HttpContext context = HttpContext.Current; 
                return (string)context.Session["msg"]; 
            }
            set
            {
                HttpContext context = HttpContext.Current;
                context.Session["msg"] = value;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中,您应该执行以下操作:

TextService.Message = "testing the whole thing";
return Redirect("/home/testing.myapp");
Run Code Online (Sandbox Code Playgroud)

在其他类中,您可以调用辅助类:

return TextService.Message;
Run Code Online (Sandbox Code Playgroud)

试试看.


Art*_*510 2

好的,所以我最终要做的就是......在我的 ashx 文件中,我添加了 IReadOnlySessionState 接口,它将很好地访问会话状态。所以它看起来像这样......

  public class getIcon : IHttpHandler, IReadOnlySessionState
Run Code Online (Sandbox Code Playgroud)