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

时间:2021-11-09 07:27:16
  • How can I get the id of the currently logged in user in MVC 5? I tried the * suggestions, but they seem to be not for MVC 5.
  • 如何在MVC 5中获取当前登录用户的id ?我尝试了*的建议,但是它们似乎不适合MVC 5。
  • Also, what is the MVC 5 best practice of assigning stuff to the users? (e.g. a User should have Items. Should I store the User's Id in Item? Can I extend the User class with an List<Item> navigation property?
  • 还有,MVC 5为用户分配东西的最佳实践是什么?(例如,用户应该有项目。我应该将用户的Id存储在项目中吗?我可以使用列表 导航属性扩展用户类吗?

I'm using "Individual User Accounts" from the MVC template.

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

Tried these:

尝试这些:

'Membership.GetUser()' is null.

“Membership.GetUser()”是零。

5 个解决方案

#1


282  

If you're coding in an ASP.NET MVC Controller, use

如果你在一个ASP中编码。净MVC控制器,使用

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

User.Identity值得一提。IsAuthenticated User.Identity。名称将在不添加上述使用语句的情况下工作。但是GetUserId()没有它不会出现。

If you're in a class other than a Controller, use

如果你在一个类中而不是一个控制器,使用

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

In the default template of MVC 5, user ID is a GUID stored as a string.

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

No best practice yet, but found some valuable info on extending the user profile:

还没有最佳实践,但是找到了一些关于扩展用户概要的有价值的信息:

#2


27  

Try something like:

尝试:

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

Works with RTM.

适用于RTM。

#3


16  

If you want the ApplicationUser object in one line of code (if you have the latest ASP.NET Identity installed), try:

如果您想要在一行代码中包含ApplicationUser对象(如果您有最新的ASP)。净身份安装),试一试:

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

You'll need the following using statements:

您将需要使用以下语句:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

#4


7  

Getting the Id is pretty straight forward and you've solved that.

得到Id很直接,你已经解决了。

Your second question though is a little more involved.

第二个问题有点复杂。

So, this is all prerelease stuff right now, but the common problem you're facing is where you're extending the user with new properties ( or an Items collection in you're question).

这都是预发布的东西,但是你面临的常见问题是你用新的属性扩展用户(或者你的问题是项目集合)。

Out of the box you'll get a file called IdentityModel under the Models folder (at the time of writing). In there you have a couple of classes; ApplicationUser and ApplicationDbContext. To add your collection of Items you'll want to modify the ApplicationUser class, just like you would if this were a normal class you were using with Entity Framework. In fact, if you take a quick look under the hood you'll find that all the identity related classes (User, Role etc...) are just POCOs now with the appropriate data annotations so they play nice with EF6.

开箱后,您将在Models文件夹(编写时)下获得一个名为IdentityModel的文件。在那里你有几节课;ApplicationUser ApplicationDbContext。要添加项目集合,您需要修改ApplicationUser类,就像您在使用实体框架时使用的普通类一样。事实上,如果您快速浏览一下,您会发现所有与身份相关的类(用户、角色等)现在都是POCOs,带有适当的数据注释,所以它们在EF6中表现得很好。

Next, you'll need to make some changes to the AccountController constructor so that it knows to use your DbContext.

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

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

Now getting the whole user object for your logged in user is a little esoteric to be honest.

现在,为您的登录用户获取整个用户对象是一个小秘密。

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

That line will get the job done and you'll be able to access userWithItems.Items like you want.

这一行将完成任务,您将能够访问userWithItems。你想要的物品,如。

HTH

HTH

#5


0  

I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.

我感受到了你的痛苦,我也在尝试做同样的事情。在我的例子中,我只想清除用户。

I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication and set the filterContext.HttpContext.User to null

我创建了一个基控制器类,我所有的控制器都继承自它。在它中,我重写了OnAuthentication并设置了filterContext.HttpContext。用户为空

That's the best I've managed to far...

这是我所能做到的最好的……

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;
        }
    }
    ...
}

#1


282  

If you're coding in an ASP.NET MVC Controller, use

如果你在一个ASP中编码。净MVC控制器,使用

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

User.Identity值得一提。IsAuthenticated User.Identity。名称将在不添加上述使用语句的情况下工作。但是GetUserId()没有它不会出现。

If you're in a class other than a Controller, use

如果你在一个类中而不是一个控制器,使用

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

In the default template of MVC 5, user ID is a GUID stored as a string.

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

No best practice yet, but found some valuable info on extending the user profile:

还没有最佳实践,但是找到了一些关于扩展用户概要的有价值的信息:

#2


27  

Try something like:

尝试:

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

Works with RTM.

适用于RTM。

#3


16  

If you want the ApplicationUser object in one line of code (if you have the latest ASP.NET Identity installed), try:

如果您想要在一行代码中包含ApplicationUser对象(如果您有最新的ASP)。净身份安装),试一试:

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

You'll need the following using statements:

您将需要使用以下语句:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

#4


7  

Getting the Id is pretty straight forward and you've solved that.

得到Id很直接,你已经解决了。

Your second question though is a little more involved.

第二个问题有点复杂。

So, this is all prerelease stuff right now, but the common problem you're facing is where you're extending the user with new properties ( or an Items collection in you're question).

这都是预发布的东西,但是你面临的常见问题是你用新的属性扩展用户(或者你的问题是项目集合)。

Out of the box you'll get a file called IdentityModel under the Models folder (at the time of writing). In there you have a couple of classes; ApplicationUser and ApplicationDbContext. To add your collection of Items you'll want to modify the ApplicationUser class, just like you would if this were a normal class you were using with Entity Framework. In fact, if you take a quick look under the hood you'll find that all the identity related classes (User, Role etc...) are just POCOs now with the appropriate data annotations so they play nice with EF6.

开箱后,您将在Models文件夹(编写时)下获得一个名为IdentityModel的文件。在那里你有几节课;ApplicationUser ApplicationDbContext。要添加项目集合,您需要修改ApplicationUser类,就像您在使用实体框架时使用的普通类一样。事实上,如果您快速浏览一下,您会发现所有与身份相关的类(用户、角色等)现在都是POCOs,带有适当的数据注释,所以它们在EF6中表现得很好。

Next, you'll need to make some changes to the AccountController constructor so that it knows to use your DbContext.

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

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

Now getting the whole user object for your logged in user is a little esoteric to be honest.

现在,为您的登录用户获取整个用户对象是一个小秘密。

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

That line will get the job done and you'll be able to access userWithItems.Items like you want.

这一行将完成任务,您将能够访问userWithItems。你想要的物品,如。

HTH

HTH

#5


0  

I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.

我感受到了你的痛苦,我也在尝试做同样的事情。在我的例子中,我只想清除用户。

I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication and set the filterContext.HttpContext.User to null

我创建了一个基控制器类,我所有的控制器都继承自它。在它中,我重写了OnAuthentication并设置了filterContext.HttpContext。用户为空

That's the best I've managed to far...

这是我所能做到的最好的……

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;
        }
    }
    ...
}