在ashx文件中,Asp.Net会话为空。

33

我正在尝试像下面展示的那样在Asp.Net ashx处理程序中访问Session变量

public void ProcessRequest (HttpContext context) {
        context.Session["VariableName"] = Id;
    }

但是上述方法中的context.Session始终为Null。我该如何在ashx文件中访问Session对象?

2个回答

97

您需要"实现" IRequiresSessionState 或者 IReadOnlySessionState 接口,前者提供对session的完全访问权限,后者提供只读访问权限。

这里我用“实现”一词引用是因为这两个接口被称为"标记接口",这意味着它们没有成员。


3
谢谢你的点赞,先生。我唯一的遗憾是只能给你一个赞。 - CountMurphy
太好了!关于“标记接口”,如果把它们做成注解不是更好吗? - everton
8
Anton指的“implement”是指具有以下代码:public class ClassName : IHttpHandler, System.Web.SessionState.IRequiresSessionState{...}。 - adinas

2
在VB中,按照Anton提到的接口(IRequiresSessionState或IReadOnlySessionState)进行实现,可以这样做:
Public Class MyAshxFile

    Implements System.Web.IHttpHandler
    Implements System.Web.SessionState.IRequiresSessionState ''need this for session variables
    Implements System.Web.SessionState.IReadOnlySessionState ''need this for session variables

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接