gpt4 book ai didi

c# - ASP MVC5 - 身份。如何获取当前 ApplicationUser 并使用此用户查询以用户为外键的表

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:58 24 4
gpt4 key购买 nike

我有一个 ASP.NET MVC 应用程序。我使用个人用户帐户和身份 API 的方式只有 canEdit 角色中的用户才能编辑数据(我的数据是产品)。 ASPNetUsers 和 Products 实体具有 1:N 关系(这只是一个示例)。因此,用户拥有(拥有)产品列表。

当用户请求 http://localhost:1111/Products 时,页面应显示该用户之前登录的产品列表。

我不确定如何获取当前的 ApplicationUser 以及如何查询产品表以获取属于用户的产品列表。

这是我的 ProductsController 的代码:

public class ProductsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();


// GET: Products
[AllowAnonymous]
public ActionResult Index()
{
string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

//How to modify these sentence to get the products of the current user??
Product product = db.Products.Find();
return View(db.Products.ToList());
}
....

最佳答案

因为您使用的是个人身份验证,所以您应该能够使用用户 ID 直接从应用程序数据库访问用户:

UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

这将从您的数据库中创建一个包含用户的对象,然后您可以简单地使用类似的方式调用它:

CurrentUser = UserManager.FindById(User.Identity.GetUserId());

要获取当前登录的用户,User 对象应自动填充登录用户的详细信息。

因为您拥有 [AllowAnonymous] 属性,您还必须确保用户实际使用 Request.IsAuthenticated 登录,否则 User 对象将为空。

将它们全部加在一起将使您的代码看起来像这样:

[AllowAnonymous]
public ActionResult Index()
{
if (Request.IsAuthenticated)
{
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
ApplicationUser currentUser = UserManager.FindById(User.Identity.GetUserId());

// assuming there is some kind of relationship between products and users
List<Product> products = db.Products.Where(p => p.User.Equals(currentUser.UserID)).ToList(); // or .email or other field from your users table

// OPTIONAL: Make sure they see something
if(products.Count ==0) // They have no related products so just send all of them
products = db.Products.ToList();

// only send the products related to that user
return View(products);
}
// User is not authenticated, send them all products
return View(db.Products.ToList());
}

关于c# - ASP MVC5 - 身份。如何获取当前 ApplicationUser 并使用此用户查询以用户为外键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35906059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com