0

我有以下示例代码可以重现我的问题:

protected void Page_Load(object sender, EventArgs e)
{
    var test = Session["test"] as string;
    if (test == null)
    {
        Session["test"] = "test";
        Response.Redirect(Request.Path, false);
    } 
    else
    {
        Session.Remove("test");
        throw new Exception();
    }
}

本质上,我希望能够从会话中删除对象,无论是否引发异常。上面的代码块将在第一个页面加载时运行良好,但是一旦发生重定向,它将继续为每个后续页面加载抛出异常。该对象实际上从未从会话中删除。

如果您将手表放在投掷上,您将看到会话对象已被删除。

编辑#1:经过更多测试后,我注意到此行为仅存在于 StateServer 状态模式中。我已经针对 InProc 进行了测试,它似乎按预期工作。我无法针对 SQL Server 模式进行测试。

4

1 回答 1

0

我相信您的问题是您将缺少值Session视为空白(或空格)。

我会推荐以下代码:

protected void Page_Load(object sender, EventArgs e)
{
    // Does the value exist in Session?
    if(null != Session["test"])
    {
        // No, so throw an exception
        throw new Exception();
    }

    // Grab the value from Session and cast it to a string
    var test = Session["test"] as string;

    // Is the string null or blank?
    if (string.IsNullOrWhiteSpace(test))
    { 
        // Yes, so give it a value of 'test' and redirect to another page
        Session["test"] = "test";
        Response.Redirect(Request.Path, false);
    } 
    else
    {
        // The value was not null or blank so rip it out of Session
        Session.Remove("test");    
    }
}
于 2013-07-09T20:10:20.833 回答