C# HttpContext.Current.Session 在 Ashx 文件中为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14181408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:58:16  来源:igfitidea点击:

HttpContext.Current.Session is null in Ashx file

c#asp.net.netsessiongeneric-handler

提问by Mosh Feu

I saw some questions (Hereand Here) but they do not answer my question. I am trying to call Ajax using "ajax.ashx" file, and in function to access Session. For some reason, the value of the Session object itself is null.

我看到了一些问题(这里这里),但他们没有回答我的问题。我正在尝试使用“ajax.ashx”文件调用 Ajax,并在函数中访问会话。出于某种原因,Session 对象本身的值是 null。

Use example:

使用示例:

Session = HttpContext.Current.Session // This is null

Or:

或者:

public virtual void ProcessRequest(HttpContext context)
{
    System.Web.SessionState.HttpSessionState Session = context.Session; 
    // This is null
}

In the Web.config:

在 Web.config 中:

<sessionState timeout="1800"></sessionState>

采纳答案by Aristos

You must add on your handler the IRequiresSessionStateon the declaration of it as:

您必须在您的处理程序IRequiresSessionState上添加它的声明为:

public class YourHandleName : IHttpHandler, IRequiresSessionState 
{
...

by default the handlers are not connected with the session to keep them minimum, by adding the IRequiresSessionStateyou attach them with the session.

默认情况下,处理程序不与会话连接以保持它们最小,通过添加IRequiresSessionState您将它们附加到会话中。