2017-07-29 21 views
0

我想創建一個ASP.NET Core Web應用程序,用戶可以在其中創建,編輯,刪除和查看目標。我能夠使用Entity Framework和Identity Framework對用戶進行身份驗證,但我想授權/顯示該用戶專門記錄的內容。現在,該頁面將顯示所有用戶創建的所有內容。如何顯示由特定用戶使用ASP.NET Core,Identity 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核心。我應該使用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被存儲在創建目標的時間。

回答

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

我居然發現這個一個相當不錯的微軟的文章這可能是更全面的,因爲它有CRUD的每個部分,以及如何爲不同的用戶角色設置授權處理程序:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/secure-data – user1869407