c# - MVC 5 全局用户帐户对象

标签 c# asp.net asp.net-mvc asp.net-mvc-4 razor

我有一个具有以下布局的应用程序。在我的共享 View 文件夹中,_Layout.cshtml_SideNav.cshtml_CurrentUser.cshtml

_Layout.cshtml 我有:

@{ Html.RenderPartialIf("_SideNav", Request.IsAuthenticated); }

_SideNav.cshtml 我有:

@{ Html.RenderPartial("_CurrentUser"); }

_CurrentUser.cshtml 我有:

<div class="login-info">
    <span>
        <a href="javascript:void(0);" id="show-shortcut" data-action="toggleShortcut">
            <img src="~/content/img/avatars/sunny.png" alt="me" class="online" />
            <span>@User.Identity.Name</span>
            <i class="fa fa-angle-down"></i>
        </a>
    </span>
</div>

我们使用 FormsAuthentication 来验证用户。我们没有使用 ASP.Net MVC 5 附带的标准 Identity 身份验证,因为我们使用的是 LDAP 服务器。

FormsAuthentication.SetAuthCookie(username, isPersistent);
.....
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(username, "Forms"), roles);

我们在 cookie 中使用 username 以便我们可以轻松地从 LDAP 服务器获取信息。

问题:@User.Identity.Name 返回该用户名。但是我需要显示用户的全名。当我们进行身份验证时,我可以访问全名。但不确定如何使用它。

如何将 AccountController 中的 FullName 值传递给 _CurrentUser.cshtml 部分 View ?有点像 @User.Identity 这样的全局容器,可以设置更多属性。

最佳答案

你可以这样使用

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                                viewModel.Email,
                                                                YOUR_ISSUE_DATE,
                                                                YOUR_EXPIRE_DATE,
                                                                viewModel.RememberMe,
                                                                JsonConvert.SerializeObject(user),
                                                                FormsAuthentication.FormsCookiePath);


string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

Response.Cookies.Add(authcookie);

关于c# - MVC 5 全局用户帐户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529401/

相关文章:

c# - 如何在 ASP.NET Web 应用程序中显示错误消息

javascript - 禁用的链接按钮仍在 asp.net web 表单中提交

c# - session 关闭后加载子对象

javascript - 根据先前的 DropDownList 选择禁用 DropDownList

asp.net - signalr ie9 后退前进按钮问题

asp.net-mvc - godaddy 中等信任级别下的 Entity Framework 6 和 System.Security.Permissions.ReflectionPermission

c# - 在 MVC 区域中时出现导航问题

asp.net-mvc - 调用 .Raise() 后获取 Elmah 中的错误 ID

c# - 在 C# 中使用 Sentry 记录未处理的异常

c# - 控制点击事件点击框