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

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

问题描述

  • 如何在 MVC 5 中获取当前登录用户的 ID?我尝试了 StackOverflow 的建议,但它们似乎不适用于 MVC 5.
  • 此外,MVC 5 向用户分配内容的最佳实践是什么?(例如,User 应该有 Items.我应该将用户的 Id 存储在 Item 中吗?我可以扩展 <具有 List 导航属性的 code>User 类?
  • 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?

我正在使用 MVC 模板中的个人用户帐户".

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

尝试过这些:

  • How do I get the current user in an MVC Application?
  • How to get the current user in ASP.NET MVC
  • Get logged in user's id - this throws the following:

'Membership.GetUser()' 为空.

'Membership.GetUser()' is null.

推荐答案

如果您在 ASP.NET MVC 控制器中编码,请使用

If you're coding in an ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

值得一提的是,User.Identity.IsAuthenticatedUser.Identity.Name 无需添加上述 using 语句即可工作.但是 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();

在MVC 5的默认模板中,用户ID是一个以字符串形式存储的GUID.

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: https://devblogs.microsoft.com/aspnet/introducing-asp-net-identity-a-membership-system-for-asp-net-applications/
  • Example solution regarding how to extend the user profile by adding an extra property: https://github.com/rustd/AspnetIdentitySample

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

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