简体   繁体   English

MVC 5-通过用户ID获取任何用户名

[英]MVC 5 - Get any username by userid

I have an MVC 5 application that has a set of objects that reference back to the user that created them using the value obtained from: 我有一个MVC 5应用程序,该应用程序具有一组对象,这些对象引用使用从以下项获得的值创建它们的用户:

User.Identity.GetUserId();

The problem is I need to be able to resolve the username for that account at any point so it can be displayed to the user when looking at a given object. 问题是我需要能够随时解析该帐户的用户名,以便在查看给定对象时可以将其显示给用户。

for clarity: I have a stored object, of which a property is UserId. 为了清楚起见:我有一个存储的对象,其属性是UserId。 I got that value from the above code at creation time. 在创建时,我从上述代码中获得了该值。 Somebody else is now logged in and needs to know the username associated with the userid that for that stored object. 现在,其他人已登录,需要知道与该存储对象的用户标识关联的用户名。

This will not work without a lookup to the where your user information is stored. 如果不查询您的用户信息的存储位置,则无法使用该功能。

You might consider implementing that lookups in a HTML helper to use it where ever you need it. 您可能会考虑在HTML帮助器中实现该查找,以在任何需要的地方使用它。

If you are using an OR-Mapper you should aim for joining the real users with your initial query. 如果使用的是OR-Mapper,则应以最初的查询加入真正的用户。

使用会话

 Session["Username"] = data.Username;

This is an old post, but I came across it with the same question as the op. 这是一篇旧文章,但我遇到了与操作员相同的问题。 In a comment he made to his own post the op said: 他在自己的帖子中发表评论,说:

assumed ... Identity framework would have ... quick access ... of doing this

I believe the framework actually does have what the op was looking for, although I'm not certain it would be called quick. 我相信该框架确实具有操作员正在寻找的东西,尽管我不确定它会被称为快速。

When a UserManager is setup there is access to a method called 设置UserManager后,可以访问称为

FindByName(username)

I used the answer in this SO C# post to clue me in to find this method. 我在这篇SO C#帖子中使用了答案,以帮助我找到这种方法。 That post was explaining how to go the other way, ie get the UserName from the UserID, but once the UserManager is setup, there are a number of Find... methods that can be used including the one noted above which is what the op was looking for. 那篇文章解释了如何走另一条路,即从UserID中获取UserName,但是一旦设置了UserManager,便可以使用多种Find ...方法,包括上面提到的一种方法,即op在寻找。

The UserManager can be setup as follows in vb.net 可以在vb.net中按以下步骤设置UserManager

Using appDb As New ApplicationDbContext
  Dim userStore = New UserStore(Of ApplicationUser)(appDb)
  Dim myUserManager = New UserManager(Of ApplicationUser)(userStore)
  Dim userID = myUserManager.FindByName(userName)
End Using

I don't know C# well enough to post that code; 我对C#不太了解,无法发布该代码。 perhaps someone else can do that. 也许其他人可以做到。 Anyway, it worked for me. 无论如何,它为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM