C# 获取登录用户的id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13994967/
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 10:19:09  来源:igfitidea点击:

Get logged in user's id

c#asp.net-mvc-4simplemembership

提问by naveed

How can I get the logged in user's UserId? I'm using the standard system generated AccountModel. I can get the username using:

如何获取登录用户的 UserId?我正在使用标准系统生成的 AccountModel。我可以使用以下方法获取用户名:

User.Identity.Name

but I don't see the UserId field. I want to use the UserId as a foreign key for another table.

但我没有看到 UserId 字段。我想使用 UserId 作为另一个表的外键。

回答by Aviatrix

The best way to do so is to use the WebSecurty class

最好的方法是使用 WebSecurty 类

var memberId = WebSecurity.GetUserId(User.Identity.Name);

and don't forget to add [InitializeSimpleMembership]on top of your controller :)

并且不要忘记添加[InitializeSimpleMembership]到您的控制器之上:)

回答by prasanthv

Try this:

尝试这个:

using Microsoft.AspNet.Identity;
User.Identity.GetUserId();

That's how its done in the partial views for current MVC (MVC5/EF6/VS2013) templates.

这就是它如何在当前 MVC (MVC5/EF6/VS2013) 模板的部分视图中完成的。

Correct me if I'm wrong, because I've seen Aviatrix's answers a lot, but what happens if more than one user has the same name in the database?

如果我错了,请纠正我,因为我经常看到 Aviatrix 的答案,但是如果数据库中有多个用户具有相同的名称会发生​​什么?

回答by Learner

Their are already very good answer but what i understood from your question is that you want to fetch data from database using id.so here is what you can do.

他们已经是很好的答案,但我从你的问题中了解到你想使用 id.so 从数据库中获取数据,所以你可以这样做。

public List<ForeignkeyTable> RV()
{
 var email = User.Identity.Name;

Usertable m = db.Uusertables.Where(x => x.user_Email == email).SingleOrDefault();

 var id = m.user_Id;

var p = db.ForeignkeyTable.Where(x => x.user_fk_id == id).ToList();


return p;

}

This way you can return all the data from database of that id in foreignkey.

通过这种方式,您可以从外键中该 id 的数据库中返回所有数据。