Search code examples
asp.net-mvcrazorsession-cookiesnullreferenceexception

Problem in sending session to view at Asp.Net MVC


I want to prevent clients to access route Home/Index when they are not logged in. So the code in my view is here:

@{
    Layout = null;
    if (Session["userId"]==null)
    {
        Response.Redirect(Url.Action("Index","Login"));

    }
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>QIndex</title>
</head>
<body>
    <div>
        <h1>Profile</h1>
        <h2>Hello @Session["userName"].ToString() </h2>
        <a href=@Url.Action("LogOut","Login")>خروج</a>
    </div>
</body>
</html>

Problem is that when i eliminate @Session["userName"].ToString() everything is alright. But when this is not eliminated, an error occurs on this line System.NullReferenceException: 'Object reference not set to an instance of an object.'. I set a break point on if (Session["userId"]==null). I realized that compiler goes to <h2>Hello @Session["userName"].ToString() </h2> before it checks the if statement and then returns to if.


Solution

  • Just remove .ToString(). It should render the string properly without it.