上传 ashx 文件 Context.Session 为 null

发布于 2024-10-09 10:53:56 字数 1103 浏览 0 评论 0原文

我的网站中有一个文件上传,这是使用 uploadify 完成的,它使用 ashx 页面将文件上传到数据库。它在 IE 中工作正常,但在 Mozilla 中上下文。Session 为 null。我还使用了 IReadOnlySessionState 读取会话。

我怎样才能像 IE 一样在 Mozilla 中获得会话。

这是我完成的 ashx 代码

public class Upload : IHttpHandler, IReadOnlySessionState 
{    
    HttpContext context;
    public void ProcessRequest(HttpContext context)
    {
        string UserID = context.Request["UserID"];

        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        XmlDocument xDoc = new XmlDocument();
        HttpPostedFile postedFile = context.Request.Files["Filedata"];
        try
        {
            if (context.Session["User"] == null || context.Session["User"].ToString() == "")
            {
                context.Response.Write("SessionExpired");
                context.Response.StatusCode = 200;
            }
            else
            {
                  // does the uploading to database
            }
        }
   }
}

在 IE 中 Context.Session["User"] 始终具有该值,但在 Mozilla 中它始终为 null

I have a file upload in my site which is done using uploadify it uses a ashx page to upload file to database.It works fine in IE but in Mozilla the context.Session is getting null.I have also used IReadOnlySessionState to read session.

how can i get session in Mozilla like IE.

here is the ashx code i have done

public class Upload : IHttpHandler, IReadOnlySessionState 
{    
    HttpContext context;
    public void ProcessRequest(HttpContext context)
    {
        string UserID = context.Request["UserID"];

        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        XmlDocument xDoc = new XmlDocument();
        HttpPostedFile postedFile = context.Request.Files["Filedata"];
        try
        {
            if (context.Session["User"] == null || context.Session["User"].ToString() == "")
            {
                context.Response.Write("SessionExpired");
                context.Response.StatusCode = 200;
            }
            else
            {
                  // does the uploading to database
            }
        }
   }
}

In IE Context.Session["User"] always have the value but in Mozilla it is always null

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

任谁 2024-10-16 10:53:56

您需要添加 sessionId 来上传 post 参数,并在 OnBeginRequest 处的 global.asax 上恢复服务器端的 ASP.NET_SessionId cookie。它实际上是Flash 和 cookies 的错误

我已经创建了用于会话和身份验证 cookie 恢复的模块,以获取工作 flash 和 asp.net 会话,所以我认为这对您很有用:

public class SwfUploadSupportModule : IHttpModule
{
    public void Dispose()
    {
        // clean-up code here.
    }

    public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(OnBeginRequest);
    }

    private void OnBeginRequest(object sender, EventArgs e)
    {
        var httpApplication = (HttpApplication)sender;

        /* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
        try
        {
            string session_param_name = "ASPSESSID";
            string session_cookie_name = "ASP.NET_SessionId";
            if (httpApplication.Request.Form[session_param_name] != null)
            {
                UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.Form[session_param_name]);
            }
            else if (httpApplication.Request.QueryString[session_param_name] != null)
            {
                UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.QueryString[session_param_name]);
            }
        }
        catch
        {
        }

        try
        {
            string auth_param_name = "AUTHID";
            string auth_cookie_name = FormsAuthentication.FormsCookieName;

            if (httpApplication.Request.Form[auth_param_name] != null)
            {
                UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.Form[auth_param_name]);
            }
            else if (httpApplication.Request.QueryString[auth_param_name] != null)
            {
                UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.QueryString[auth_param_name]);
            }
        }
        catch
        {
        }            
    }

    private void UpdateCookie(HttpApplication application, string cookie_name, string cookie_value)
    {
        var httpApplication = (HttpApplication)application;

        HttpCookie cookie = httpApplication.Request.Cookies.Get(cookie_name);
        if (null == cookie)
        {
            cookie = new HttpCookie(cookie_name);
        }
        cookie.Value = cookie_value;
        httpApplication.Request.Cookies.Set(cookie);
    }
}

此外,您还需要在 web.config 中注册上述模块:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <add name="SwfUploadSupportModule" type="namespace.SwfUploadSupportModule, application name" />
  </modules>
</system.webServer>

You need to add sessionId to uploadify post params and restore ASP.NET_SessionId cookie on the server side on global.asax at OnBeginRequest. It is actually bug with flash and cookies.

I have created module for session and auth cookie restore, to get work flash and asp.net session, so i think it will be useful for your:

public class SwfUploadSupportModule : IHttpModule
{
    public void Dispose()
    {
        // clean-up code here.
    }

    public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(OnBeginRequest);
    }

    private void OnBeginRequest(object sender, EventArgs e)
    {
        var httpApplication = (HttpApplication)sender;

        /* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
        try
        {
            string session_param_name = "ASPSESSID";
            string session_cookie_name = "ASP.NET_SessionId";
            if (httpApplication.Request.Form[session_param_name] != null)
            {
                UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.Form[session_param_name]);
            }
            else if (httpApplication.Request.QueryString[session_param_name] != null)
            {
                UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.QueryString[session_param_name]);
            }
        }
        catch
        {
        }

        try
        {
            string auth_param_name = "AUTHID";
            string auth_cookie_name = FormsAuthentication.FormsCookieName;

            if (httpApplication.Request.Form[auth_param_name] != null)
            {
                UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.Form[auth_param_name]);
            }
            else if (httpApplication.Request.QueryString[auth_param_name] != null)
            {
                UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.QueryString[auth_param_name]);
            }
        }
        catch
        {
        }            
    }

    private void UpdateCookie(HttpApplication application, string cookie_name, string cookie_value)
    {
        var httpApplication = (HttpApplication)application;

        HttpCookie cookie = httpApplication.Request.Cookies.Get(cookie_name);
        if (null == cookie)
        {
            cookie = new HttpCookie(cookie_name);
        }
        cookie.Value = cookie_value;
        httpApplication.Request.Cookies.Set(cookie);
    }
}

Also than you need register above module at web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <add name="SwfUploadSupportModule" type="namespace.SwfUploadSupportModule, application name" />
  </modules>
</system.webServer>
月光色 2024-10-16 10:53:56

Context.Session 为 null.. 因为与 HttpHandler 的连接有另一个 Context.Session
(调试并尝试:fileInput 中的 Context.Session.SessionId 与 Upload.ashx 中的 Context.Session.SessionId 不同)!

我建议一种解决方法:传递对第二个会话中所需元素的引用(在我的示例中,我使用 sessionId 变量传递原始 SessionId

....
var sessionId = "<%=Context.Session.SessionID%>";
var theString = "other param,if needed";
$(document).ready(function () {
    $('#fileInput').uploadify({
        'uploader': '<%=ResolveUrl("~/uploadify/uploadify.swf")%>',
        'script': '<%=ResolveUrl("~/Upload.ashx")%>',
        'scriptData': { 'sessionId': sessionId, 'foo': theString },
        'cancelImg': '<%=ResolveUrl("~/uploadify/cancel.png")%>',
 ....

并在 . .ashx 文件。

public void ProcessRequest(HttpContext context)
{
    try
    {
       HttpPostedFile file = context.Request.Files["Filedata"];
       string sessionId = context.Request["sessionId"].ToString();
      ....

如果您需要共享复杂元素,请使用 Context.Application 而不是 Context.Session,并使用原始 SessionID:Context.Application["SharedElement"+SessionID]

Context.Session is null.. because connection to HttpHandler has another Context.Session
(debug and try: Context.Session.SessionId in where is the fileInput is different from Context.Session.SessionId in Upload.ashx)!

I suggest a workaround: pass a reference to the elements you need in the second session ( in my sample i pass the original SessionId using sessionId variable)

....
var sessionId = "<%=Context.Session.SessionID%>";
var theString = "other param,if needed";
$(document).ready(function () {
    $('#fileInput').uploadify({
        'uploader': '<%=ResolveUrl("~/uploadify/uploadify.swf")%>',
        'script': '<%=ResolveUrl("~/Upload.ashx")%>',
        'scriptData': { 'sessionId': sessionId, 'foo': theString },
        'cancelImg': '<%=ResolveUrl("~/uploadify/cancel.png")%>',
 ....

and use this items in .ashx file.

public void ProcessRequest(HttpContext context)
{
    try
    {
       HttpPostedFile file = context.Request.Files["Filedata"];
       string sessionId = context.Request["sessionId"].ToString();
      ....

If you need to share complex elements use Context.Application instead of Context.Session, using original SessionID: Context.Application["SharedElement"+SessionID]

黄昏下泛黄的笔记 2024-10-16 10:53:56

这可能是服务器无法设置或发送回客户端的原因。

回到较低级别 - 使用网络诊断工具,例如 FiddlerWireshark 检查发送到/来自您的服务器的流量并比较 IE 和 Firefox 之间的差异。

查看标头以确保 cookie 和表单值按预期发送回服务器。

It's likely to be something failing to be set by the server or sent back on the client.

Step back to a lower level - use a network diagnostic tool such as Fiddler or Wireshark to examine the traffic being sent to/from your server and compare the differences between IE and Firefox.

Look at the headers to ensure that cookies and form values are being sent back to the server as expected.

泡沫很甜 2024-10-16 10:53:56

我创建了一个函数来检查会话是否已过期,然后将其作为参数传递到 uploadify 的脚本数据和 ashx 文件中,我检查该参数以查看会话是否存在。如果它返回会话已过期,则上传将不会进行这对我有用。使用它没有发现任何问题。希望能解决我的问题

I have created a function to check session have expired and then pass that as a parameter in script-data of uploadify and in ashx file i check that parameter to see whether session exists or not.if it returns session have expired then upload will not take place.It worked for me. Did not find any issues using that. hope that solve my issue

波浪屿的海角声 2024-10-16 10:53:56

我对 .ashx 文件也有类似的问题。解决方案是处理程序必须实现 IReadOnlySessionState(用于只读访问)或 IRequiresSessionState(用于读写访问)。例如:

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

这些接口不需要任何额外的代码,而是充当框架的标记。

希望这有帮助。

乔纳森

I had a similar problem with an .ashx file. The solution was that the handler has to implement IReadOnlySessionState (for read-only access) or IRequiresSessionState (for read-write access). eg:

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

These Interfaces do not need any additional code but act as markers for the framework.

Hope that this helps.

Jonathan

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文