开发者

Session values lost in an ASP.NET application

I created HttpHandler class in ASP.NET and configured a website to handle any request with the *.test path.

public class GameHandler : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public void ProcessRequest (HttpContext context)
    {
        if (context.Request.ContentType == "application/json; charset=utf-8")
        {
            ...
            switch (parameters ["type"])
            {
                case "Setup":
                    result = Setup (context);

                    break;

                case "DoStep":
                    result = DoStep (context, parameters);

                    break;
             }
             ...
         }
         else
             context.Response.Write (@"
                  <html>
                      <head>
                      </head>
                      <body>
                          <!-- some HTML -->
                      </body>
                  </html>"); // this is returned on first request 
    }

In the Setup method I have such a code:

context.Session ["Game"] = new Game ();

In the DoStep method however, context.Session.Count = 0 and context.Session["Game"] is NULL. In client side I use jquery to call these functions. Such a call looks like this:

 $.ajax({
        url: "/test.test",  
        type: "POST",
        data: "{'type':'Setup'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (开发者_开发知识库result) {...}
 });

 $.ajax({
        url: "/test.test",  
        type: "POST",
        data: "{'type':'DoStep','row':'" + row + "','column':'" + column + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {...}
 });

I suspect the problem is that ASP.NET doesn't know these requests sent from javascript belong to the same session and that's why the Session values are lost. I think that I would need to send back some cookie information or something for the next request to be identified but the fact is I don't have any idea.

Any help is really appreciated.


In case anyone encounters this problem I would like to specify that this happened because I use some file manipulation in the ProcessRequest method.

var doc = XDocument.Load (@"c:\XO_Game_Website\bin\test.xml"); 
if (context.Session ["something"] == null) 
{ 
    context.Session.Add("something", "something"); 
    doc.Root.Element ("xxx").Value = "null"; 
} 
else 
{
    doc.Root.Element ("xxx").Value = "not null";
}
doc.Save("path"); 

Once I removed the doc.Save("path"); from the method, everything just worked fine. Nonetheless I can't figure out why on earth would the file manipulation code reset the session values.

Happy coding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜