【问题标题】:How display content created by specific user using ASP.NET Core, Identity Framework with Entity Framework如何显示特定用户使用 ASP.NET Core、Identity Framework 和 Entity Framework 创建的内容
【发布时间】:2018-01-05 18:16:09
【问题描述】:

我正在尝试创建一个 ASP.NET Core Web 应用程序,人们可以在其中创建、编辑、删除和查看目标。我能够将实体框架与身份框架一起使用来验证用户身份,但我想授权/显示该用户专门记录的内容。现在,该页面将显示所有用户创建的所有内容。

这是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 的位置。

【问题讨论】:

    标签: entity-framework asp.net-core asp.net-identity


    【解决方案1】:

    您需要在 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());
    }
    

    【讨论】:

    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2020-03-29
    • 1970-01-01
    • 2016-12-21
    相关资源
    最近更新 更多