Search code examples
entity-frameworkasp.net-coreasp.net-identity

How display content created by specific user using ASP.NET Core, Identity Framework with Entity Framework


I am trying to create an ASP.NET Core web application where people can create, edit, delete, and view goals. I was able to use Entity Framework with Identity Framework to authenticate users but I want to authorize/display content specifically recorded by that user. Right now, the page will display everything created by all users.

This is the index method in the Goals controller.

[Authorize]
// GET: Goals
public async Task<IActionResult> Index()
{
    return View(await _context.Goal.ToListAsync());
}

Here is some Goals controller code that pulls in 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;
    }

I have read a few different approaches with regular old Asp.Net but nothing the says what the best practice is for ASP.NET Core. Should I be using a LINQ?

Here is the goal model:

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 is where the user id is being stored at the time a goal is created.


Solution

  • You need to add a filter in you LINQ Query like this:

    [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());
    }