Ada*_*abo 154 c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity
User
应该有Items
,我应该存储在用户Id
的Item
?我可以扩展User
与类List<Item>
导航属性?我正在使用MVC模板中的"个人用户帐户".
试过这些:
'Membership.GetUser()'为空.
Ada*_*abo 306
如果您在ASP.NET MVC控制器中进行编码,请使用
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
Run Code Online (Sandbox Code Playgroud)
值得一提的是User.Identity.IsAuthenticated
,User.Identity.Name
无需添加上述using
声明即可使用.但GetUserId()
没有它就不会存在.
如果您在控制器以外的其他课程中,请使用
HttpContext.Current.User.Identity.GetUserId();
Run Code Online (Sandbox Code Playgroud)
在MVC 5的默认模板中,用户ID是存储为字符串的GUID.
还没有最佳实践,但在扩展用户配置文件时找到了一些有价值的信息:
Identity
:http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx小智 28
尝试类似的东西:
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
Run Code Online (Sandbox Code Playgroud)
适用于RTM.
fir*_*ape 19
如果您希望将ApplicationUser对象放在一行代码中(如果安装了最新的ASP.NET标识),请尝试:
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
Run Code Online (Sandbox Code Playgroud)
您需要以下使用语句:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
Run Code Online (Sandbox Code Playgroud)
获得ID非常简单,你已经解决了这个问题.
你的第二个问题涉及到更多.
所以,现在这都是预发布的东西,但是您面临的常见问题是您使用新属性(或者您的问题中的Items集合)扩展用户.
开箱即用,您将获得一个IdentityModel
在Models文件夹下调用的文件(在撰写本文时).在那里你有几个班级; ApplicationUser
和ApplicationDbContext
.要添加你的集合,Items
你想要修改ApplicationUser
该类,就像您使用Entity Framework时的正常类一样.事实上,如果你快速浏览一下,你会发现所有与身份相关的类(用户,角色等......)现在都只是POCO,并带有相应的数据注释,因此它们与EF6相得益彰.
接下来,您需要对AccountController
构造函数进行一些更改,以便它知道使用您的DbContext.
public AccountController()
{
IdentityManager = new AuthenticationIdentityManager(
new IdentityStore(new ApplicationDbContext()));
}
Run Code Online (Sandbox Code Playgroud)
现在,为您的登录用户获取整个用户对象是坦率的,说实话.
var userWithItems = (ApplicationUser)await IdentityManager.Store.Users
.FindAsync(User.Identity.GetUserId(), CancellationToken.None);
Run Code Online (Sandbox Code Playgroud)
该行将完成工作,您将能够访问 userWithItems.Items
像您想要的那样.
HTH
归档时间: |
|
查看次数: |
203194 次 |
最近记录: |