【问题标题】:How to display user name from session in layout page in MVC?如何在 MVC 的布局页面中显示会话中的用户名?
【发布时间】:2016-06-10 16:21:15
【问题描述】:

我正在制作 mvc 项目,并在布局页面中显示来自会话变量的用户名。如果会话变量为空,那么它将显示登录链接。见下面的代码。

_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>
}

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

控制器动作

    [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);
        }
    }

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

【问题讨论】:

  • 删除 if 条件中用户 ID 的 ''.ToString'。
  • 只需使用'HttpContext.Current.Session["UserId"]'
  • 是的..它的工作..谢谢你..
  • 干杯!我会将此作为答案发布

标签: asp.net-mvc asp.net-mvc-4 session


【解决方案1】:

这是可能的决定之一:

@if(!String.IsNullOrEmpty((string)HttpContext.Current.Session["UserName"]))
{
using (Html.BeginForm("Logout", "Login", FormMethod.Post, new { id="logoutForm", @class = "navbar-centre" }))
{
<table align="right">
<tr>
<td> Welcome : @Session["UserName"] !!</td>
                                                                                       </tr>
</table>
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
}
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>
}

在您的布局页面中进行这些更改。

【讨论】:

    【解决方案2】:

    如果C# 6.0(默认在VS2015)可用,则可以使用空条件运算符获得更优雅的代码:

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

    另外,我认为如果未经身份验证的用户需要空字符串,则可以跳过合并 (??)。

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

    【讨论】:

      【解决方案3】:

      删除 if 条件中的“.ToString()”。会话变量已经是一个字符串。只需使用,HttpContext.Current.Session["UserId"]

      由于 session 变量为 null,当你尝试做 ToString 时,它会抛出 null 异常。

      【讨论】:

        【解决方案4】:

        替换

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

        @if (!String.IsNullOrEmpty((string)HttpContext.Current.Session["UserId"]))
        

        【讨论】:

          【解决方案5】:

          这个

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

          应该替换为

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

          您的代码中的问题是 .ToString() 只能在非空引用上调用,而您的代码目前无法阻止这种情况。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-01-23
            • 2014-10-23
            • 2012-01-15
            • 2014-04-25
            • 2022-01-13
            • 2019-10-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多