How to display user name from session in layout page in MVC?

23,403

Solution 1

This

@if (HttpContext.Current.Session["UserId"].ToString() != null && 
     HttpContext.Current.Session["UserId"].ToString() != "")

should be replaced with

@if (HttpContext.Current.Session["UserId"] != null &&
...

The problem in your code is that .ToString() can only be called on a non-null reference and your code doesn't prevent this at the moment.

Solution 2

If C# 6.0 (by default in VS2015) is available, null conditional operator can be used to obtain a more elegant code:

@HttpContext.Current.Session["UserId"]?.ToString() ?? "anonymous"

Also, I think that coalesce (??) can be skipped if empty string is required for non-authenticated users.

@HttpContext.Current.Session["UserId"]?.ToString()

Solution 3

Remove ".ToString()" in the if condition. Session variable is already a string. Just use, HttpContext.Current.Session["UserId"]

Since the session variable is null, when you try to do ToString, it throws the null exception.

Share:
23,403
Karan Patel
Author by

Karan Patel

I live as a software engineer😎 Angular😍 is my hobby. You can reach out to me by linked profile. LinkedIn: https://www.linkedin.com/in/karan-patel-96b02b50

Updated on January 17, 2020

Comments

  • Karan Patel
    Karan Patel over 4 years

    i am making mvc project and in layout page i am displaying user name from session variable. If session variable is null then it will display login link. see below code.

    _Layout.cshtml

    @if (HttpContext.Current.Session["UserId"].ToString() != null && HttpContext.Current.Session["UserId"].ToString() != "")
    {
        using (Html.BeginForm("LogOff", "Home", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
        {
            <ul class="nav navbar-nav navbar-right">
                <li>
                    <p><b>@Session["UserName"]</b></p>
                </li>
                <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
            </ul>
        }
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li>@Html.ActionLink("Register", "Register", "Home", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
            <li>@Html.ActionLink("Log in", "Login", "Home", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
        </ul>
    }
    

    i set session in login action as below.

    Controller Action

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel login)
        {
            User user = new User();
            user = db.Users.Where(x => x.UserName == login.UserName && x.Password == login.Password).FirstOrDefault();
    
            if(user != null)
            {
                Session["UserName"] = user.UserName;
                Session["UserId"] = user.UserName;
                return RedirectToAction("Index");
            }
            else
            {
                return View(login);
            }
        }
    

    but i am getting Object reference not set to an instance of an object. error see attached image.

    Error of Object reference