如何获取当前用户,以及如何在MVC5使用User类? [英] How to get current user, and how to use User class in MVC5?

查看:223
本文介绍了如何获取当前用户,以及如何在MVC5使用User类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 我怎样才能在当前登录用户的ID中的 MVC 5 ?我试过StackOverflow的建议,但他们似乎不MVC 5.

  • 此外,什么是对用户分配的东西的MVC 5最佳做法? (如用户应该有项目。我应该存储用户的编号项目我可以延长用户列表与LT类;项目> 导航属性?

我使用的是个人用户帐户从MVC模板。

尝试这些:


  

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 have Items. Should I store the User's Id in Item? Can I extend the User class with an List<Item> navigation property?

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

Tried these:

'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 and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() 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:

这篇关于如何获取当前用户,以及如何在MVC5使用User类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆