我正在尝试创建一个 ASP.NET Core Web 应用程序,人们可以在其中创建、编辑、删除和查看目标。我能够使用带有 Identity Framework 的 Entity Framework 来对用户进行身份验证,但我想授权/显示该用户专门记录的内容。现在,该页面将显示所有用户创建的所有内容。
这是Goals
控制器中的索引方法。
[Authorize]
// GET: Goals
public async Task<IActionResult> Index()
{
return View(await _context.Goal.ToListAsync());
}
这是一些Goals
引入的控制器代码UserManager
:
public class GoalsController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context;
public GoalsController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
我已经阅读了一些使用常规旧 Asp.Net 的不同方法,但没有说明 ASP.NET Core 的最佳实践是什么。我应该使用LINQ
?
这是目标模型:
public class Goal
{
[Key]
public int TaskID { get; set; }
public string UserID { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
public bool IsSubGoal { get; set; }
[Display(Name = "Due Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? DueDate { get; set; }
[Display(Name = "Created On")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime CreatedOn { get; set; }
[Display(Name = "Last Modified")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? LastModified { get; set; }
}
UserID
是在创建目标时存储用户 ID 的位置。
您需要在 LINQ 查询中添加一个过滤器,如下所示:
[Authorize]
// GET: Goals
public async Task<IActionResult> Index()
{
// the instruction below this comment will help to get the Id of the current authenticated user.
// Make sure you derive your controller from Microsoft.AspNetCore.Mvc.Controller
var userId = await _userManager.GetUserIdAsync(HttpContext.User);
return View(await _context.Goal.Where(g => g.UserID == userId).ToListAsync());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句