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.

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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With