会话提出了一个看不见的问题?

时间:2013-09-11 09:23:28

标签: c# .net session

这是我的代码:

public partial class context_userpanel_IoSocial : iUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["oom-user"] = "utente";

        if ((UserOOM)Session["oom-user"] == null)
        {
            Response.Write("not logged");
        }

        Response.Write("logged");
    }
}

Session["oom-user"]中的对象属于UserOOM类型。但是如果我在会话中存储一个字符串,我看不到任何Response.Write。为什么这个?我该如何解决?

5 个答案:

答案 0 :(得分:1)

您没有看到任何Response.Write,因为对UserOOM的强制转换失败,并且运行时异常会导致应用程序失效。

如果你想在同一个会话变量中存储不同类型的数据(这可能不是最好的主意),你必须使用is / as代替直接投射例如:

if (Session["oom-user"] is UserOOM)
{
    // something 
}
else if (Session["oom-user"] is string)
{
    // something else
}

答案 1 :(得分:1)

  

Session["oom-user"]中的对象属于UserOOM类型。

不是来自您的代码:

 Session["oom-user"] = "utente";

这会在string中放入Session["oom-user"]并使类型转换失败并出现异常。

答案 2 :(得分:0)

"utente"类型的字符串UserOOM是?没有。

你需要修复if条款,如果你只是想检查它是null,你根本不需要施放:

    Session["oom-user"] = "utente";
    if (Session["oom-user"] == null)
    {
        Response.Write("not logged");
    }
    else
    {
        Response.Write("logged");
    }

这种“认证”显然不是很安全:)

答案 3 :(得分:0)

引发不可见异常的对象不是Session对象,异常不可见。

想象一下:你有一个object类型的变量,它存储一个字符串。

object variable = "Test";

使用convert运算符,然后将其值转换为不兼容的类型 (不是stringstring的子类,但string是密封类型,只有string才能工作):

SomeOtherClass asAstring = (SomeOtherClass)variable;

由于InvalidCastException运营商选择了as而失败了:

SomeOtherClass thisWillBeNUll = variable as SomeOtherClass;

所以你看,它不是抛出异常的Session对象。 当你写

if ((SomeClass)Session["somekey"] == null) { ... }

你实际上在写:

object thisIsOk = Session["somekey"]; // this is not the throwing place
SomeClass temp = (SomeClass)thisIsOk; // this is the throwing place

// and you won't be reaching any code until the closest `catch` clause up the stack
if (temp == null) {
}

答案 4 :(得分:0)

protected void Page_Load(object sender, EventArgs e)
{
    object obj = Session["oom-user"];
    if (obj is UserOOM)
    {
        Response.Write("logged in");
    }
    else
    {
        Response.Write("not logged in");
    }
}