【问题标题】:Why doesn't Session.Remove remove the session object if followed by a thrown exception?如果 Session.Remove 后跟抛出异常,为什么不删除会话对象?
【发布时间】:2013-07-10 04:31:22
【问题描述】:

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

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 模式进行测试。

【问题讨论】:

    标签: c# asp.net session-state


    【解决方案1】:

    我相信您的问题是您将 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");    
        }
    }
    

    【讨论】:

    • Karl,我认为我的示例可能有点令人困惑。如果会话对象不存在,我不打算抛出异常。我的意图是表明未处理的(在我的示例中是强制的)异常会阻止会话对象被删除。我还修复了检查 null 而不是空字符串的条件。
    猜你喜欢
    • 1970-01-01
    • 2022-09-30
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多