繁体   English   中英

如何在ASP.NET MVC中查找与特定用户有关的数据

[英]How to find the data related to a specific user in ASP.NET MVC

我现在正在学习ASP.NET MVC 5,并且正在做一个小项目来提高我的知识。

使用实体框架,尽管有登录和注册功能,但直到现在我都没有看到用于Users的表。

例如,我想知道:当我想要显示与特定用户有关的数据时该怎么办? 用这样的代码:

public ActionResult MyAnnoncement()
{
    if (!User.Identity.IsAuthenticated)
    {
        return View("~/Views/Account/Login.cshtml");
    }
    else  
    {
        return View(db.Voitures.ToList());
    }
}

您可以使用User.Identity.GetUserId()从AspNetUsers表中获取用户的ID,然后像这样填充User对象:

ApplicationDbContext db = new ApplicationDbContext();
string uid = User.Identity.GetUserId();
ApplicationUser u = db.Users.Find(uid);

请注意,您需要添加“ using Microsoft.AspNet.Identity;”。 在代码顶部使用User.Identity.GetUserId()。

您需要一个UserManager实例“ ApplicationUser可以与您的情况不同,其他对象也可以。然后您可以执行类似的操作

var user = UserManager.FindById(User.Identity.GetUserId()); 

用户对象具有您的数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM