如何在MVC的布局页面中显示会话中的用户名?

Kar*_*tel 2 asp.net-mvc session asp.net-mvc-4

我正在制作mvc项目,在布局页面我正在显示会话变量的用户名.如果session变量为null,则它将显示登录链接.见下面的代码.

_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>
}
Run Code Online (Sandbox Code Playgroud)

我在登录操作中设置会话如下.

控制器动作

    [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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我得到的对象引用未设置为对象的实例.错误见附图.

对象引用错误

Wik*_*hla 5

这个

@if (HttpContext.Current.Session["UserId"].ToString() != null && 
     HttpContext.Current.Session["UserId"].ToString() != "")
Run Code Online (Sandbox Code Playgroud)

应该换成

@if (HttpContext.Current.Session["UserId"] != null &&
...
Run Code Online (Sandbox Code Playgroud)

您的代码中的问题是.ToString()只能在非空引用上调用,而您的代码目前不会阻止此操作.