检索属于经过身份验证的用户的条目
Retrieve entries that belong to the authenticated user
我正在使用 ASP.NET Core with Identity 和 Entity Framework Core。
如何找回属于认证用户的宠物?
[Authorize]
public class HomeController : Controller
{
private readonly PetContext _context;
public HomeController(PetContext context)
{
_context = context;
}
public IActionResult Index()
{
// User.Identity.IsAuthenticated -> true
// User.Identity.Name --> bob@example.com
ViewData.Model = _context.Pets.Where(pet => /* ...? */);
return View();
}
}
Pets
对象是否应该包含类型为 string
的 "PetOwner" 属性,其中包含与 User.Identity.Name
进行比较的电子邮件地址?
或者我是否应该从 UserManager
中获取一个 IdentityUser
对象并对其进行处理?也许 Id
属性?我应该有一个扩展 IdentityUser
的 ApplicationUser
对象吗?
Should I have an ApplicationUser object that extends IdentityUser?
是的!您的 ApplicationUser
和 Pet
类 应该如下所示:
public class ApplicationUser : IdentityUser
{
public List<Pet> Pets {get; set;}
}
public class Pet
{
public int PetId {get; set;}
........
public string UserId {get; set;}
public ApplicationUser User {get; set;}
}
然后更新您在 Startup.ConfigureServices
中的身份注册,如下所示:
services.AddDefaultIdentity<ApplicationUser>() //<-- Replace `IdentityUser` with `ApplicationUser`
.AddEntityFrameworkStores<AppliclationDbContext>()
.AddDefaultTokenProviders();
那么您的查询应该如下:
var loggedInUserId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
List<Pet> userPets = _context.Pets.Where(pet => pet.UserId == loggedInUserId).ToList();
我正在使用 ASP.NET Core with Identity 和 Entity Framework Core。 如何找回属于认证用户的宠物?
[Authorize]
public class HomeController : Controller
{
private readonly PetContext _context;
public HomeController(PetContext context)
{
_context = context;
}
public IActionResult Index()
{
// User.Identity.IsAuthenticated -> true
// User.Identity.Name --> bob@example.com
ViewData.Model = _context.Pets.Where(pet => /* ...? */);
return View();
}
}
Pets
对象是否应该包含类型为 string
的 "PetOwner" 属性,其中包含与 User.Identity.Name
进行比较的电子邮件地址?
或者我是否应该从 UserManager
中获取一个 IdentityUser
对象并对其进行处理?也许 Id
属性?我应该有一个扩展 IdentityUser
的 ApplicationUser
对象吗?
Should I have an ApplicationUser object that extends IdentityUser?
是的!您的 ApplicationUser
和 Pet
类 应该如下所示:
public class ApplicationUser : IdentityUser
{
public List<Pet> Pets {get; set;}
}
public class Pet
{
public int PetId {get; set;}
........
public string UserId {get; set;}
public ApplicationUser User {get; set;}
}
然后更新您在 Startup.ConfigureServices
中的身份注册,如下所示:
services.AddDefaultIdentity<ApplicationUser>() //<-- Replace `IdentityUser` with `ApplicationUser`
.AddEntityFrameworkStores<AppliclationDbContext>()
.AddDefaultTokenProviders();
那么您的查询应该如下:
var loggedInUserId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
List<Pet> userPets = _context.Pets.Where(pet => pet.UserId == loggedInUserId).ToList();