如何获取当前用户,以及如何在MVC5使用User类? [英] How to get current user, and how to use User class in MVC5?
问题描述
- 我怎样才能在当前登录用户的ID中的 MVC 5 ?我试过StackOverflow的建议,但他们似乎不MVC 5.
- 此外,什么是对用户分配的东西的MVC 5最佳做法? (如
用户
应该有项目
。我应该存储用户的编号
在项目
我可以延长用户
与列表与LT类;项目>
导航属性?
我使用的是个人用户帐户从MVC模板。
尝试这些:
- How我获取当前用户在MVC应用程序?
- 如何获得当前用户在Asp.Net MVC
- 获取登录的用户的ID - 这将引发以下内容:
Membership.GetUser()'为空。
块引用>解决方案如果您是在一个ASP.NET MVC编码控制器,使用
使用Microsoft.AspNet.Identity;...User.Identity.GetUserId();
值得一提的是,
User.Identity.IsAuthenticated
和User.Identity.Name
无添加上述提到的将工作使用
语句。但GetUserId()
不会是present离不开它。如果你在一个类中的其他比控制器,用
HttpContext.Current.User.Identity.GetUserId();
在MVC 5的默认模板,用户ID存储为一个字符串GUID。
没有最好的做法呢,却发现了一些有价值的信息上扩展用户配置文件:
身份
概述:<一href=\"http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx\">http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx- 有关如何通过添加额外的属性来扩展用户配置文件示例解决方案:<一href=\"https://github.com/rustd/AspnetIdentitySample\">https://github.com/rustd/AspnetIdentitySample
- How can I get the id of the currently logged in user in MVC 5? I tried the StackOverflow suggestions, but they seem to be not for MVC 5.
- Also, what is the MVC 5 best practice of assigning stuff to the users? (e.g. a
User
should haveItems
. Should I store the User'sId
inItem
? Can I extend theUser
class with anList<Item>
navigation property?I'm using "Individual User Accounts" from the MVC template.
Tried these:
- How do I get the current user in an MVC Application?
- How to get current user in Asp.Net MVC
- Get logged in user's id - this throws the following:
'Membership.GetUser()' is null.
解决方案If you're coding in an ASP.NET MVC Controller, use
using Microsoft.AspNet.Identity; ... User.Identity.GetUserId();
Worth mentioning that
User.Identity.IsAuthenticated
andUser.Identity.Name
will work without adding the above mentionedusing
statement. ButGetUserId()
won't be present without it.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.
No best practice yet, but found some valuable info on extending the user profile:
- Overview of
Identity
: http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx- Example solution regarding how to extend the user profile by adding an extra property: https://github.com/rustd/AspnetIdentitySample
这篇关于如何获取当前用户,以及如何在MVC5使用User类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!