简体   繁体   English

三元检查中的C#空引用异常

[英]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. 即使进行三元检查,我也会在userInfo上出现Null Reference Exception错误。 The other weird part is that when I inspect firstName and lastName they both show "???". 另一个奇怪的部分是,当我检查firstName和lastName时,它们都显示“ ???”。

@{ 
    // 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. 评论:我已经在MVC中开发了几个小型应用程序,但这是我的第一个基于用户的身份应用程序。 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. 首先,我们不应该将用户信息存储在Session中以检查用户是否已通过身份验证。 It is very fragile, and it cannot use ASP.NET MVC's build-in Authorize attribute. 它非常脆弱,不能使用ASP.NET MVC的内置Authorize属性。

Ideally, you want to use ASP.NET Identity . 理想情况下,您要使用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 . 如果您不熟悉ASP.NET Identity,则可能想观看Scott Allen的免费ASP.NET MVC 5基础课程

If you already have an existing user database, and do not want to use ASP.NET Identity, you could just use Owin Authentication Middleware. 如果您已经有一个现有的用户数据库,并且不想使用ASP.NET Identity,则可以只使用Owin身份验证中间件。 You can read more at this SO answer, and here is the working sample code. 你可以阅读更多在 SO回答, 这里是工作示例代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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