日期:2014-05-17  浏览次数:20332 次

ashx页面使用session值问题
aspx.cs:

public partial class lazytest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["name"] = "DMJ";
    }
}

aspx:

<p id="txtbox">还没有</p>
  
    <script>

        $.get("Handler.ashx", function (result) { $("#txtbox").html(result); }); 
    </script>

.ashx:

 public class Handler : IHttpHandler,IRequiresSessionState {
    
    public void ProcessRequest (HttpContext context) {
        
        context.Response.ContentType = "text/plain";
        
        if (HttpContext.Current.Session["name"] != null)
        {
            string myname =HttpContext.Current.Session["name"].ToString();
            context.Response.Write(myname);
            context.Response.End();
        }
        else
            context.Response.Write("没有收到session");
        
    }


问题是,在调试的时候,在ashx那边一直显示session["name"]为空,这是为什么呢?把httpcontext.current.session换成context.session也不可以
session c# ashx

------解决方案--------------------
在 Session["name"] = "DMJ";设个断点
在if (HttpContext.Current.Session["name"] != null)也设个断点

看哪句先执行?
------解决方案--------------------
改js代码
<script>

        //在页面加载完毕后再取ashx里的数据
        $(document).ready(function()
        {
            $.get("Handler.ashx", function (result) { $("#txtbox").html(result); }); 
        });
    </script>

------解决方案--------------------

function PostMethod(){//post代码}


后台load事件里可以
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>PostMethod()</script>");





------解决方案--------------------
我咋一直这样用都行呢,你确认你的js代码是和后台代码的页面是在同一个页面上?