C# 如何获取当前用户,以及如何在 MVC5 中使用 User 类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18448637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:14:15  来源:igfitidea点击:

How to get current user, and how to use User class in MVC5?

c#asp.netasp.net-mvcasp.net-mvc-5asp.net-identity

提问by Adam Szabo

  • 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 Usershould have Items. Should I store the User's Idin Item? Can I extend the Userclass with an List<Item>navigation property?
  • 如何在MVC 5 中获取当前登录用户的 ID ?我尝试了 StackOverflow 的建议,但它们似乎不适用于 MVC 5。
  • 另外,将东西分配给用户的 MVC 5 最佳实践是什么?(例如,User应该有Items。我应该将用户存储在IdItem吗?我可以User使用List<Item>导航属性扩展类吗?

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

我正在使用 MVC 模板中的“个人用户帐户”。

Tried these:

试过这些:

'Membership.GetUser()' is null.

'Membership.GetUser()' 为空。

采纳答案by Adam Szabo

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

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

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticatedand User.Identity.Namewill work without adding the above mentioned usingstatement. But GetUserId()won't be present without it.

值得一提的是User.Identity.IsAuthenticatedUser.Identity.Name无需添加上述using语句即可工作。但GetUserId()没有它就不会出现。

If you're in a class other than a Controller, use

如果您在 Controller 以外的类中,请使用

HttpContext.Current.User.Identity.GetUserId();

In the default template of MVC 5, user ID is a GUID stored as a string.

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

No best practice yet, but found some valuable info on extending the user profile:

还没有最佳实践,但发现了一些关于扩展用户配置文件的有价值的信息:

回答by EightyOne Unite

Getting the Id is pretty straight forward and you've solved that.

获取 Id 非常简单,您已经解决了这个问题。

Your second question though is a little more involved.

你的第二个问题虽然涉及更多。

So, this is all prerelease stuff right now, but the common problem you're facing is where you're extending the user with new properties ( or an Items collection in you're question).

所以,这现在都是预发布的东西,但您面临的常见问题是您使用新属性(或您有问题的 Items 集合)扩展用户。

Out of the box you'll get a file called IdentityModelunder the Models folder (at the time of writing). In there you have a couple of classes; ApplicationUserand ApplicationDbContext. To add your collection of Itemsyou'll want to modify the ApplicationUserclass, just like you would if this were a normal class you were using with Entity Framework. In fact, if you take a quick look under the hood you'll find that all the identity related classes (User, Role etc...) are just POCOs now with the appropriate data annotations so they play nice with EF6.

开箱即用,您将IdentityModel在 Models 文件夹下获得一个文件(在撰写本文时)。在那里你有几个类;ApplicationUserApplicationDbContext。要添加您的集合,Items您需要修改ApplicationUser该类,就像您在 Entity Framework 中使用的普通类一样。事实上,如果您快速浏览一下底层,您会发现所有与身份相关的类(用户、角色等)现在都只是具有适当数据注释的 POCO,因此它们与 EF6 配合得很好。

Next, you'll need to make some changes to the AccountControllerconstructor so that it knows to use your DbContext.

接下来,您需要对AccountController构造函数进行一些更改,以便它知道使用您的 DbContext。

public AccountController()
{
    IdentityManager = new AuthenticationIdentityManager(
    new IdentityStore(new ApplicationDbContext()));
}

Now getting the whole user object for your logged in user is a little esoteric to be honest.

老实说,现在为您的登录用户获取整个用户对象有点深奥。

    var userWithItems = (ApplicationUser)await IdentityManager.Store.Users
    .FindAsync(User.Identity.GetUserId(), CancellationToken.None);

That line will get the job done and you'll be able to access userWithItems.Itemslike you want.

该线路将完成工作,您将能够随意访问userWithItems.Items

HTH

HTH

回答by Derek Tomes

I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.

我感受到你的痛苦,我正在尝试做同样的事情。就我而言,我只想清除用户。

I've created a base controller class that all my controllers inherit from. In it I override OnAuthenticationand set the filterContext.HttpContext.User to null

我创建了一个基本控制器类,我的所有控制器都继承自该类。在其中我覆盖OnAuthentication并设置filterContext.HttpContext.User to null

That's the best I've managed to far...

这是我迄今为止设法做到的最好的...

public abstract class ApplicationController : Controller   
{
    ...
    protected override void OnAuthentication(AuthenticationContext filterContext)
    {
        base.OnAuthentication(filterContext); 

        if ( ... )
        {
            // You may find that modifying the 
            // filterContext.HttpContext.User 
            // here works as desired. 
            // In my case I just set it to null
            filterContext.HttpContext.User = null;
        }
    }
    ...
}

回答by Rok Berme?

Try something like:

尝试类似:

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

Works with RTM.

与 RTM 一起使用。

回答by firecape

If you want the ApplicationUser object in one line of code (if you have the latest ASP.NET Identity installed), try:

如果您希望在一行代码中使用 ApplicationUser 对象(如果您安装了最新的 ASP.NET Identity),请尝试:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You'll need the following using statements:

您将需要以下 using 语句:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

回答by Hari Lakkakula

        string userName="";
        string userId = "";
        int uid = 0;
        if (HttpContext.Current != null && HttpContext.Current.User != null
                  && HttpContext.Current.User.Identity.Name != null)
        {
            userName = HttpContext.Current.User.Identity.Name;              
        }
        using (DevEntities context = new DevEntities())
        {

              uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
            return uid;
        }

        return uid;

回答by Duan Walker

if anyone else has this situation: i am creating an email verification to log in to my app so my users arent signed in yet, however i used the below to check for an email entered on the login which is a variation of @firecape solution

如果其他人有这种情况:我正在创建电子邮件验证以登录我的应用程序,因此我的用户尚未登录,但是我使用以下内容检查登录时输入的电子邮件,这是@firecape 解决方案的变体

 ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);

you will also need the following:

您还需要以下内容:

using Microsoft.AspNet.Identity;

and

using Microsoft.AspNet.Identity.Owin;

回答by Bhupinder Yadav

In .Net MVC5 core 2.2, I use HttpContext.User.Identity.Name . It worked for me.

在 .Net MVC5 核心 2.2 中,我使用 HttpContext.User.Identity.Name 。它对我有用。

回答by kelvin nyadzayo

This is how I got an AspNetUser Id and displayed it on my home page

这就是我如何获得 AspNetUser Id 并将其显示在我的主页上

I placed the following code in my HomeController Index() method

我将以下代码放在我的 HomeController Index() 方法中

ViewBag.userId = User.Identity.GetUserId();

In the view page just call

在视图页面中只需调用

ViewBag.userId 

Run the project and you will be able to see your userId

运行该项目,您将能够看到您的 userId