0

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.

Peter B
  • 22,460
  • 5
  • 32
  • 69
ChathurawinD
  • 756
  • 1
  • 13
  • 35
  • 1
    Basically this error said that your session not set thus it can not accessible. check your session is set (Having value) in controller before you try to access from view or you can simply check is session null to avoid exception in view page. – Parvez Mar 07 '19 at 07:15
  • 1
    The syntax is correct, your session is most likely to be unset. First, check whether your linq query is assignign the correct type to the userDetails object, then check for its values – Davide Vitali Mar 07 '19 at 07:17
  • 1
    On which line exactly do you get the error? – ckuri Mar 07 '19 at 07:19
  • @ckuri on the view – Davide Vitali Mar 07 '19 at 07:20
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ian Kemp Mar 07 '19 at 08:27
  • @ckuri

    Username : @Session["userName"].ToString()

    On this line.
    – ChathurawinD Mar 07 '19 at 08:36
  • @ian-kemp Thanks for just pointing it out. But that question only has only one answer which says nullexception occurrance when handling session. In that answer it points out what will happen, but that doesn't say which syntax to be used, in what way the declarations should be done to avoid this kind of an error. Everyone here are not experts on everything, if that was the case, this kind of a forum wouldn't needed to be built. If I were you, and if my intention was to help, I would stay away till others help to solve the error, without down voting unreasonably. – ChathurawinD Mar 07 '19 at 09:52

3 Answers3

2

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>
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Thank you this saved my day. Do you suggest any other alternative procedure to avoid these kind of errors happening, I mean when declaring and accessing the session objects. – ChathurawinD Mar 07 '19 at 09:55
  • In your controllers you'll have to be defensive, e.g. do null checks, possibly combined with soft type casting, like this: `var value = Session["xyz"] as string; if (value != null) ...` – Peter B Mar 07 '19 at 10:28
1

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>
Fatikhan Gasimov
  • 903
  • 2
  • 16
  • 40
  • Note that using **`?.`** requires at least a **C# 6 compatible** .NET Framework (v4.6 or higher) on the server where this will run, because usually MVC Views are JIT-compiled on the web server. – Peter B Mar 07 '19 at 09:31
  • @FatikhanGasimov When I change code segment like this it doesn't give me any error or exception, but in the home it displays "?.ToString()" part with the user id. – ChathurawinD Mar 07 '19 at 09:37
-1

In Global.Asax file set the folllowing

protected void Application_PostAuthorizeRequest()
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57