首页 文章

如何获取当前用户,以及如何在MVC5中使用User类?

提问于
浏览
149
  • 如何在 MVC 5 中获取当前登录用户的ID?我尝试了StackOverflow的建议,但它们似乎不适用于MVC 5 .

  • 另外,为用户分配东西的MVC 5最佳做法是什么? (例如 User 应该有 Items . 我应该在 Item 中存储用户的 Id 吗?我可以使用 List<Item> 导航属性扩展 User 类吗?

我正在使用MVC模板中的“个人用户帐户” .

试过这些:

'Membership.GetUser()'为空 .

6 回答

  • 295

    如果您在ASP.NET MVC控制器中进行编码,请使用

    using Microsoft.AspNet.Identity;
    
    ...
    
    User.Identity.GetUserId();
    

    值得一提的是 User.Identity.IsAuthenticatedUser.Identity.Name 可以在不添加上述 using 语句的情况下工作 . 但没有它, GetUserId() 将不存在 .

    如果您在控制器以外的其他课程中,请使用

    HttpContext.Current.User.Identity.GetUserId();
    

    在MVC 5的默认模板中,用户ID是存储为字符串的GUID .

    还没有最佳实践,但在扩展用户配置文件时找到了一些有 Value 的信息:

  • 17

    尝试类似的东西:

    var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
    var userManager = new UserManager<ApplicationUser>(store);
    ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
    

    适用于RTM .

  • 7

    如果您希望将ApplicationUser对象放在一行代码中(如果安装了最新的ASP.NET标识),请尝试:

    ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
    

    您需要以下使用语句:

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    
  • 0

    获得ID非常简单,你已经解决了这个问题 .

    你的第二个问题涉及到更多 .

    所以,现在这都是预发布的东西,但是您面临的常见问题是您使用新属性(或者您的问题中的Items集合)扩展用户 .

    开箱即用,您将在Models文件夹下(在撰写本文时)获得一个名为 IdentityModel 的文件 . 在那里你有几个 class ; ApplicationUserApplicationDbContext . 要添加 Items 的集合,您需要修改 ApplicationUser 类,就像您使用Entity Framework时的正常类一样 . 事实上,如果你快速浏览一下,你会发现所有与身份相关的类(用户,角色等......)现在都只是POCO,并带有相应的数据注释,因此它们与EF6相得益彰 .

    接下来,您需要对 AccountController 构造函数进行一些更改,以便它知道使用您的DbContext .

    public AccountController()
    {
        IdentityManager = new AuthenticationIdentityManager(
        new IdentityStore(new ApplicationDbContext()));
    }
    

    现在,为您的登录用户获取整个用户对象是坦率的,说实话 .

    var userWithItems = (ApplicationUser)await IdentityManager.Store.Users
        .FindAsync(User.Identity.GetUserId(), CancellationToken.None);
    

    该行将完成工作,您将能够像您想要的那样访问 userWithItems.Items .

    HTH

  • 28

    我感觉到你的痛苦,我正在尝试做同样的事情 . 在我的情况下,我只想清除用户 .

    我创建了一个基本控制器类,我的所有控制器都继承自该类 . 在其中我覆盖 OnAuthentication 并设置 filterContext.HttpContext.User to null

    那是我迄今为止所做的最好的......

    public abstract class ApplicationController : Controller   
    {
        ...
        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            base.OnAuthentication(filterContext); 
    
            if ( ... )
            {
                // You may find that modifying the 
                // filterContext.HttpContext.User 
                // here works as desired. 
                // In my case I just set it to null
                filterContext.HttpContext.User = null;
            }
        }
        ...
    }
    
  • 0
    string userName="";
            string userId = "";
            int uid = 0;
            if (HttpContext.Current != null && HttpContext.Current.User != null
                      && HttpContext.Current.User.Identity.Name != null)
            {
                userName = HttpContext.Current.User.Identity.Name;              
            }
            using (DevEntities context = new DevEntities())
            {
    
                  uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
                return uid;
            }
    
            return uid;
    

相关问题