C# 会话引发了一个无形的陷阱?

C# 会话引发了一个无形的陷阱?,c#,.net,session,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) { R

这是我的代码:

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");
    }
}

会话[“oom user”]
中的对象类型为
UserOOM
。但如果我在会话中存储字符串,我看不到任何
响应。为什么会这样?我如何修复它呢?

您看不到任何
响应。写入
,因为转换到
UserOOM
失败,运行时异常导致应用程序关闭

如果要在同一会话变量中存储不同类型的数据(这可能不是最好的主意),则必须使用
is
/
as
,而不是在取出数据时直接转换,例如:

if (Session["oom-user"] is UserOOM)
{
    // something 
}
else if (Session["oom-user"] is string)
{
    // something else
}
会话[“oom user”]
中的对象类型为
UserOOM

不是从您的代码:

 Session["oom-user"] = "utente";
这将在
会话[“oom user”]
中放置一个
字符串
,并使类型转换异常失败。

用户oom
类型的字符串
“utene”
?没有

您需要修复
if
子句,如果您只想检查它是否为
null
,则根本不需要强制转换:

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

这种“身份验证”显然不是很安全:)

引发不可见异常的不是
会话
对象,异常也不是不可见的

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

object variable = "Test";
然后使用
convert
运算符将其值强制转换为不兼容的类型 (它不是
string
string
的子类,但
string
是一种密封类型,因此只要
string
就可以了):

as
操作员所做的操作相比,
InvalidCastException
失败:

SomeOtherClass thisWillBeNUll = variable as SomeOtherClass;
因此,抛出异常的不是
会话
对象。 当你写作时

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) {
}

字符串
UserOOM
类型的“utene”
?否。然后需要修复
if
if(会话[“oom用户”]==null)…
@TimSchmelter可能他定义了一个从
string
UserOOM
的impicit强制转换?可能他定义了一个从
string
UserOOM
的impicit强制转换?@markzzz您可以将
作为
进行强制转换,然后不会引发异常,但如果无法进行强制转换,结果将为空。您可以尝试/捕获在这个方法中,或者在global.asax…中实现常规异常事件。。。。不清楚您希望在这里发生什么。“…一个运行时异常导致应用程序关闭。”-无论如何,我们会终止当前请求…@Joe:当然,它不会导致整个应用程序服务器关闭。:-)
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) {
}
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");
    }
}