如何在ASP中获取用户对象的用户id。净MVC吗?

时间:2021-11-13 03:38:36

I have some tables that have a uniqueidentifier UserID that relates to aspnet_Users.UserID. When the user submits some data for those tables, since the controller method has an [Authorize] I get a User object. I can get the username with User.Identity.Name, but how do I get the UserID to be able to establish (the ownership) relationship?

我有一些表,它有一个与aspnet_Users.UserID相关的唯一标识符UserID。当用户向这些表提交一些数据时,因为控制器方法有一个[授权]我得到一个用户对象。我可以用User.Identity获取用户名。名称,但是如何让UserID能够建立(所有权)关系?

11 个解决方案

#1


86  

It seems you cannot get it from the User object but you can get it this way:

似乎你无法从用户对象中获得它,但你可以这样获得:

Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;

#2


30  

Here is the solution:

这是解决方案:

Include:

包括:

using Microsoft.AspNet.Identity;

Then use extension methods:

然后使用扩展方法:

User.Identity.GetUserId();

#3


27  

Firstly, this answer is not strictly an MVC answer, but an ASP.NET answer. The fact that your site is MVC is irrelevant to solving the problem, in this case.

首先,这个答案不是严格意义上的MVC,而是一个ASP。净的答案。在本例中,站点是MVC这一事实与解决问题无关。


Hmm. I'm not very sure how you are handling your users in your system but it sounds like you using the (very evil) asp.net membership provider that comes out of the box with .net. This is hinted by the fact that you said

嗯。我不太确定你是如何在你的系统中处理你的用户的,但是听起来好像你在使用(非常邪恶的)asp.net成员资格提供商。net。net。这暗示了你说的事实。

  • aspnet_Users.UserID
  • aspnet_Users.UserID
  • UserID is a uniqueidentifier (read: GUID).
  • UserID是一个惟一的标识符(读作GUID)。

With the default forms authentication system, which uses the default FormsIdentity, it only has a single property called Name (as you correctly noted). This means it has only one value where to place some unique user information. In your case, you are putting Name/UserName/DisplayName, in the Name property. I'm assuming this name is their Display Name and it is unique. Whatever value you are putting in here, it HAS TO BE UNIQUE.

使用默认的表单验证系统(使用默认的FormsIdentity),它只有一个名为Name的属性(正如您正确地指出的那样)。这意味着它只有一个值可以放置一些唯一的用户信息。在您的例子中,您将Name/UserName/DisplayName放在Name属性中。我假设这个名字是他们的显示名,它是唯一的。无论你在这里输入什么值,它都必须是唯一的。

From this, you can grab the user's guid.

从这里,您可以获取用户的guid。

Check this out.

看看这个。

using System.Web.Security;

....

// NOTE: This is a static method .. which makes things easier to use.
MembershipUser user = Membership.GetUser(User.Identity.Name);
if (user == null)
{
    throw new InvalidOperationException("User [" + 
        User.Identity.Name + " ] not found.");
}

// Do whatever u want with the unique identifier.
Guid guid = (Guid)user.ProviderUserKey;

So, every time you wish to grab the user information, you need to grab it from the database using the static method above.

因此,每当您希望获取用户信息时,都需要使用上面的静态方法从数据库中获取它。

Read all about the Membership class and MembershipUser class on MSDN.

阅读MSDN上的会员类和会员用户类。

Bonus Answer / Suggestion

As such, i would CACHE that result so you don't need to keep hitting the database.

因此,我将缓存结果,这样您就不需要继续访问数据库。

... cont from above....
Guid guid = (Guid)user.ProviderUserKey;

Cache.Add(User.Identity.Name, user.UserID); // Key: Username; Value: Guid.

Otherwise, you can create your own Identity class (which inherits from IIdentity) and add your own custom properties, like UserID. Then, whenever you authenticate (and also on every request) you can set this value. Anyway, this is a hard core solution, so go with the caching, right now.

否则,您可以创建自己的标识类(它继承自IIdentity)并添加自己的自定义属性,如UserID。然后,无论何时进行身份验证(也在每个请求上),都可以设置该值。无论如何,这是一个核心解决方案,所以现在就使用缓存。

HTH

HTH

#4


18  

User.Identity is an IPrincipal - typically of type System.Web.Security.FormsIdentity

用户。标识是IPrincipal——通常是System.Web.Security.FormsIdentity类型

It doesn't know anything about UserIDs - it's just an abstraction of the concept of an 'identity'.

它对用户标识一无所知——它只是对“身份”概念的抽象。

The IIdentity interface only has 'Name' for a user, not even 'Username'.

IIdentity界面只对用户有“名称”,甚至“用户名”也没有。

If you're using MVC4 with the default SimpleMembershipProvider you can do this:

如果你使用MVC4和默认的simplembershipprovider你可以这样做:

WebSecurity.GetUserId(User.Identity.Name)   // User is on ControllerBase

(Where WebSecurity is in the nuget package Microsoft.AspNet.WebPages.WebData in WebMatrix

(WebSecurity在nuget包中,Microsoft.AspNet.WebPages)。在WebMatrix WebData

You can also use

您还可以使用

WebSecurity.CurrentUserName
WebSecurity.CurrentUserId

(if you're using ASPNetMembershipProvider which is the older more complex ASPNET membership system then see the answer by @eduncan911)

(如果您使用的是ASPNetMembershipProvider,它是较老的更复杂的ASPNET成员资格系统,请参见@eduncan911)

#5


11  

If you are using the ASP.NET Membership (which in turn uses the IPrincipal object):

如果您正在使用ASP。净会员(依次使用IPrincipal对象):

using System.Web.Security;
{
  MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
  Guid guid = (Guid)user.ProviderUserKey;
}

User.Identity always returns the state of the current user, logged in or not.

用户。标识总是返回当前用户的状态,登录与否。

Anonymous or not, etc. So a check for is logged in:

匿名或不记名,等等。因此检查登录:

if (User.Identity.IsAuthenticated)
{
  ...
}

So, putting it all together:

所以,把它们放在一起

using System.Web.Security;
{
  if (User.Identity.IsAuthenticated)
  {
    MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
    Guid guid = (Guid)user.ProviderUserKey;
  }
}

#6


6  

Best Option to Get User ID

获取用户ID的最佳选项

Add Below references

添加下面的引用

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;*

public myFunc()
{
   .....
   // Code which will give you user ID is 
   var tmp = User.Identity.GetUserId();

}

#7


3  

If you are using your own IPrincipal object for authorization, you just need to cast it to access the Id.

如果您正在使用自己的IPrincipal对象进行授权,那么只需强制转换它来访问Id。

For example:

例如:

public class MyCustomUser : IPrincipal
{
    public int UserId {get;set;}

    //...Other IPrincipal stuff
}

Here is a great tutorial on creating your own Form based authentication.

这里有一个关于创建基于表单的身份验证的很棒的教程。

http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx

http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx

That should get you on the right path to creating an authentication cookie for your user and accessing your custom user data.

这将使您走上正确的道路,为您的用户创建一个身份验证cookie,并访问您的自定义用户数据。

#8


2  

using System.Web.Security;

MembershipUser user = Membership.GetUser(User.Identity.Name); 
int id = Convert.ToInt32(user.ProviderUserKey);

#9


1  

Its the ProviderUserKey property.

其ProviderUserKey属性。

System.Web.Security.MembershipUser u;
u.ProviderUserKey

#10


1  

Simple....

简单....

int userID = WebSecurity.CurrentUserId;

#11


0  

Usually you can just use WebSecurity.currentUserId, but if you're in AccountController just after the account has been created and you want to use the user id to link the user to some data in other tables then WebSecurity.currentUserId (and all of the solutions above), unfortunately, in that case returns -1, so it doesn't work.

通常你只需要使用网络安全。currentUserId,但如果你是在AccountController,帐户创建后,你想要使用用户id将用户链接到其他表中的一些数据,然后WebSecurity。不幸的是,currentUserId(以及上面所有的解决方案)返回-1,所以它不能工作。

Luckily in this case you have the db context for the UserProfiles table handy, so you can get the user id by the following:

幸运的是,在这种情况下,您有了UserProfiles表的db上下文,因此您可以通过以下方法获取用户id:

UserProfile profile = db.UserProfiles.Where(
    u => u.UserName.Equals(model.UserName)
).SingleOrDefault();

I came across this case recently and this answer would have saved me a whole bunch of time, so just putting it out there.

我最近遇到了这个案例,这个答案会节省我很多时间,所以把它写出来。

#1


86  

It seems you cannot get it from the User object but you can get it this way:

似乎你无法从用户对象中获得它,但你可以这样获得:

Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;

#2


30  

Here is the solution:

这是解决方案:

Include:

包括:

using Microsoft.AspNet.Identity;

Then use extension methods:

然后使用扩展方法:

User.Identity.GetUserId();

#3


27  

Firstly, this answer is not strictly an MVC answer, but an ASP.NET answer. The fact that your site is MVC is irrelevant to solving the problem, in this case.

首先,这个答案不是严格意义上的MVC,而是一个ASP。净的答案。在本例中,站点是MVC这一事实与解决问题无关。


Hmm. I'm not very sure how you are handling your users in your system but it sounds like you using the (very evil) asp.net membership provider that comes out of the box with .net. This is hinted by the fact that you said

嗯。我不太确定你是如何在你的系统中处理你的用户的,但是听起来好像你在使用(非常邪恶的)asp.net成员资格提供商。net。net。这暗示了你说的事实。

  • aspnet_Users.UserID
  • aspnet_Users.UserID
  • UserID is a uniqueidentifier (read: GUID).
  • UserID是一个惟一的标识符(读作GUID)。

With the default forms authentication system, which uses the default FormsIdentity, it only has a single property called Name (as you correctly noted). This means it has only one value where to place some unique user information. In your case, you are putting Name/UserName/DisplayName, in the Name property. I'm assuming this name is their Display Name and it is unique. Whatever value you are putting in here, it HAS TO BE UNIQUE.

使用默认的表单验证系统(使用默认的FormsIdentity),它只有一个名为Name的属性(正如您正确地指出的那样)。这意味着它只有一个值可以放置一些唯一的用户信息。在您的例子中,您将Name/UserName/DisplayName放在Name属性中。我假设这个名字是他们的显示名,它是唯一的。无论你在这里输入什么值,它都必须是唯一的。

From this, you can grab the user's guid.

从这里,您可以获取用户的guid。

Check this out.

看看这个。

using System.Web.Security;

....

// NOTE: This is a static method .. which makes things easier to use.
MembershipUser user = Membership.GetUser(User.Identity.Name);
if (user == null)
{
    throw new InvalidOperationException("User [" + 
        User.Identity.Name + " ] not found.");
}

// Do whatever u want with the unique identifier.
Guid guid = (Guid)user.ProviderUserKey;

So, every time you wish to grab the user information, you need to grab it from the database using the static method above.

因此,每当您希望获取用户信息时,都需要使用上面的静态方法从数据库中获取它。

Read all about the Membership class and MembershipUser class on MSDN.

阅读MSDN上的会员类和会员用户类。

Bonus Answer / Suggestion

As such, i would CACHE that result so you don't need to keep hitting the database.

因此,我将缓存结果,这样您就不需要继续访问数据库。

... cont from above....
Guid guid = (Guid)user.ProviderUserKey;

Cache.Add(User.Identity.Name, user.UserID); // Key: Username; Value: Guid.

Otherwise, you can create your own Identity class (which inherits from IIdentity) and add your own custom properties, like UserID. Then, whenever you authenticate (and also on every request) you can set this value. Anyway, this is a hard core solution, so go with the caching, right now.

否则,您可以创建自己的标识类(它继承自IIdentity)并添加自己的自定义属性,如UserID。然后,无论何时进行身份验证(也在每个请求上),都可以设置该值。无论如何,这是一个核心解决方案,所以现在就使用缓存。

HTH

HTH

#4


18  

User.Identity is an IPrincipal - typically of type System.Web.Security.FormsIdentity

用户。标识是IPrincipal——通常是System.Web.Security.FormsIdentity类型

It doesn't know anything about UserIDs - it's just an abstraction of the concept of an 'identity'.

它对用户标识一无所知——它只是对“身份”概念的抽象。

The IIdentity interface only has 'Name' for a user, not even 'Username'.

IIdentity界面只对用户有“名称”,甚至“用户名”也没有。

If you're using MVC4 with the default SimpleMembershipProvider you can do this:

如果你使用MVC4和默认的simplembershipprovider你可以这样做:

WebSecurity.GetUserId(User.Identity.Name)   // User is on ControllerBase

(Where WebSecurity is in the nuget package Microsoft.AspNet.WebPages.WebData in WebMatrix

(WebSecurity在nuget包中,Microsoft.AspNet.WebPages)。在WebMatrix WebData

You can also use

您还可以使用

WebSecurity.CurrentUserName
WebSecurity.CurrentUserId

(if you're using ASPNetMembershipProvider which is the older more complex ASPNET membership system then see the answer by @eduncan911)

(如果您使用的是ASPNetMembershipProvider,它是较老的更复杂的ASPNET成员资格系统,请参见@eduncan911)

#5


11  

If you are using the ASP.NET Membership (which in turn uses the IPrincipal object):

如果您正在使用ASP。净会员(依次使用IPrincipal对象):

using System.Web.Security;
{
  MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
  Guid guid = (Guid)user.ProviderUserKey;
}

User.Identity always returns the state of the current user, logged in or not.

用户。标识总是返回当前用户的状态,登录与否。

Anonymous or not, etc. So a check for is logged in:

匿名或不记名,等等。因此检查登录:

if (User.Identity.IsAuthenticated)
{
  ...
}

So, putting it all together:

所以,把它们放在一起

using System.Web.Security;
{
  if (User.Identity.IsAuthenticated)
  {
    MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
    Guid guid = (Guid)user.ProviderUserKey;
  }
}

#6


6  

Best Option to Get User ID

获取用户ID的最佳选项

Add Below references

添加下面的引用

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;*

public myFunc()
{
   .....
   // Code which will give you user ID is 
   var tmp = User.Identity.GetUserId();

}

#7


3  

If you are using your own IPrincipal object for authorization, you just need to cast it to access the Id.

如果您正在使用自己的IPrincipal对象进行授权,那么只需强制转换它来访问Id。

For example:

例如:

public class MyCustomUser : IPrincipal
{
    public int UserId {get;set;}

    //...Other IPrincipal stuff
}

Here is a great tutorial on creating your own Form based authentication.

这里有一个关于创建基于表单的身份验证的很棒的教程。

http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx

http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx

That should get you on the right path to creating an authentication cookie for your user and accessing your custom user data.

这将使您走上正确的道路,为您的用户创建一个身份验证cookie,并访问您的自定义用户数据。

#8


2  

using System.Web.Security;

MembershipUser user = Membership.GetUser(User.Identity.Name); 
int id = Convert.ToInt32(user.ProviderUserKey);

#9


1  

Its the ProviderUserKey property.

其ProviderUserKey属性。

System.Web.Security.MembershipUser u;
u.ProviderUserKey

#10


1  

Simple....

简单....

int userID = WebSecurity.CurrentUserId;

#11


0  

Usually you can just use WebSecurity.currentUserId, but if you're in AccountController just after the account has been created and you want to use the user id to link the user to some data in other tables then WebSecurity.currentUserId (and all of the solutions above), unfortunately, in that case returns -1, so it doesn't work.

通常你只需要使用网络安全。currentUserId,但如果你是在AccountController,帐户创建后,你想要使用用户id将用户链接到其他表中的一些数据,然后WebSecurity。不幸的是,currentUserId(以及上面所有的解决方案)返回-1,所以它不能工作。

Luckily in this case you have the db context for the UserProfiles table handy, so you can get the user id by the following:

幸运的是,在这种情况下,您有了UserProfiles表的db上下文,因此您可以通过以下方法获取用户id:

UserProfile profile = db.UserProfiles.Where(
    u => u.UserName.Equals(model.UserName)
).SingleOrDefault();

I came across this case recently and this answer would have saved me a whole bunch of time, so just putting it out there.

我最近遇到了这个案例,这个答案会节省我很多时间,所以把它写出来。