ChathurawinD
ChathurawinD

Reputation: 784

Accessing session info gives System.NullReferenceException

I'm bit new to ASP.net c# MVC. I'm trying to create a login application and create a session.In my application I have a login controller. In the login controller I read logged in user's data to session variables like in the following code segment.

[HttpPost]
public ActionResult Authorize(MVCFirst.Models.User userModel)
{
    using (MVCNewEntities db = new MVCNewEntities())
    {
        var userDetails = db.Users.Where(x => x.UserName == userModel.UserName && x.UserPWD == userModel.UserPWD).FirstOrDefault();
        if (userDetails == null)
        {
            userModel.LoginErrorMessage = "Incorrect useer name and password.";
            return View("Index", userModel);
        }
        else
        {
            Session["userID"] = userDetails.UserID;
            Session["userName"] = userDetails.UserName;
            return RedirectToAction("Index","Home");
        }
    }
}

My HomeController has Index which is an ActionResult. In the View of the HomeController I try to read Session values of the session to html header like in the following code segment.

<body>
    <div> 
        <h1>Dashboard</h1>
        <h3>Username : @Session["userName"].ToString()</h3>
        <h3>User ID : @Session["userID"].ToString()</h3>
        <a href="@Url.Action("LogOut","Login")">Logout</a>
    </div>
</body>

When I compile the app it doesn't give any error. It build successful. But when I run it, it throws an exception. The message in the exception says the following.

Message "Object reference not set to an instance of an object."

What I'm missing here? What's the mistake that I've done here? Further explanation. This didn't occur when I try to login. This occurred when I run the application for the first time.

Upvotes: 0

Views: 1283

Answers (3)

Peter B
Peter B

Reputation: 24146

You can just omit the .ToString().

In MVC, doing @someObj will display nothing for null objects, and it will implicitly call .ToString() on anything else.

<div> 
    <h1>Dashboard</h1>
    <h3>Username : @Session["userName"]</h3>
    <h3>User ID  : @Session["userID"]</h3>
</div>

Upvotes: 2

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

In Global.Asax file set the folllowing

protected void Application_PostAuthorizeRequest()
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

Upvotes: -1

Fatikhan Gasimov
Fatikhan Gasimov

Reputation: 943

just try to use this (Object?.ToString())

<body>
    <div> 
        <h1>Dashboard</h1>
        <h3>Username : @Session["userName"]?.ToString()</h3>
        <h3>User ID : @Session["userID"]?.ToString()</h3>
        <a href="@Url.Action("LogOut","Login")">Logout</a>
    </div>
</body>

Upvotes: 1

Related Questions