【问题标题】:How to fetch data about current user in ASP .NET MVC?如何在 ASP .NET MVC 中获取有关当前用户的数据?
【发布时间】:2017-07-06 18:33:52
【问题描述】:

所以,我在 ApplicationUser 类中添加了一个新参数,称为 SocialName。我想在用户登录时在右上角显示它。在那里,我们有这段代码:

@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

现在问题是,我想显示当前用户用户名以外的参数。我发现将模型传递给 Partial View 是有问题的,因为我需要为每一个动作都这样做,否则我将有 Null Reference。你有什么想法吗?

【问题讨论】:

    标签: c# .net asp.net-mvc razor identity


    【解决方案1】:

    您可以通过 Html.Action() 方法轻松地在部分视图中显示有关用户的信息,而无需将信息传递给每个操作。例如:

    您的页面/布局/...:

    <ul class="nav navbar-nav navbar-right">
        @Html.Action("HeaderUserInfo", "Common")
    </ul>
    

    CommonController.cs:

    public ActionResult HeaderUserInfo()
    {
        var user = _workContext.CurrentUser; //get info about user
        var model = new HeaderUserInfoModel
        {
            Username = user.Username,
            UserId = user.Id
        };
        return PartialView(model);
    }
    

    和部分视图 HeaderUserInfo.cshtml:

    @model Models.Common.HeaderUserInfoModel
    
    <span><i class="icon fa fa-user"></i> @Model.Username</span>    
    

    【讨论】:

    • CurrentUser 属性无效,不存在。我应该在 CommonController 构造函数中初始化数据库以外的东西吗?喜欢用户管理器?
    【解决方案2】:

    您可以通过此代码获取用户:

    ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager&lt;ApplicationUserManager&gt;().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

    您可以在控制器或视图中使用它,然后您可以使用具有所有属性的用户。

    【讨论】:

      【解决方案3】:

      您好,这里是解决您问题的链接。看来您可以使用简单的扩展方法获得输出。

      请点击以下链接,因为提问者遇到了同样的问题,最后提供了很好的解决方案。希望对你也有帮助。

      https://forums.asp.net/t/1957500.aspx?How+to+access+custom+Identity+or+ApplicationUser+properties+

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 2019-06-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-03
        相关资源
        最近更新 更多