简体   繁体   中英

C# Null Reference Exception on ternary check

I am so confused as to why this is happenning in my application. I have an object I am getting from Session storage however in some cases it may not exist so I am doing some ternary checks. Even with the ternary checks I am erroring out with a Null Reference Exception on userInfo. The other weird part is that when I inspect firstName and lastName they both show "???".

@{ 
    // Session storage for user info
    var userInfo = Session["UserInfo"] as UserInfo;

    var firstName = userInfo != null ? userInfo.FirstName : "???";
    var lastName = userInfo != null ? userInfo.LastName : "???";
}

<div>
    @firstName @lastName // Errors here with object reference not set to an instance of an object. 'userInfo' was null
</div>

Am I crazy? I swear this is how I could check against null problems.

Comment: I've developed several small scale apps in MVC but this is my first user based identity application. I want to be able to access user information wherever they are at in the application. Do I need principle to accomplish this?

First of all, we should not store user information in Session to check whether user is authenticated or not. It is very fragile, and it cannot use ASP.NET MVC's build-in Authorize attribute.

Ideally, you want to use ASP.NET Identity . If you are new to ASP.NET Identity, you might want to watch free ASP.NET MVC 5 Fundamentals course by Scott Allen .

If you already have an existing user database, and do not want to use ASP.NET Identity, you could just use Owin Authentication Middleware. You can read more at this SO answer, and here is the working sample code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM