簡體   English   中英

如何在 .net core 模型中訪問當前用戶和數據庫上下文

[英]How to access current User and database context in .net core Model

我有一個帶有方法的模型,我想獲取當前的 UserID 並可以訪問數據庫上下文。

public class Annonce
{
    public int ID { get; set; }
    
    ...

    public bool AnnonceDansFavoris(UserManager<ApplicationUser> UserManager)
    {
        // Recherche du user ID courant
        string userID = UserManager.GetUserId(ClaimTypes.NameIdentifier);

        var _context = (PatrimoineClickDbContext)ValidationContext.GetService(typeof(ApplicationDbContext));

        
        return (_context.Favoris.Any(f => (f.CreePar == userID) && (f.AnnonceID == ID)));
    }
}   

但它不起作用:(

你能告訴我我該怎么做嗎?

謝謝

這是我的錯誤信息

我無法訪問 HttpContext 類的 User 屬性

我無法訪問 ValidationContext.GetService

我認為您傳遞了錯誤的參數: 在此處輸入圖像描述 要獲取 UserId,您可以嘗試:

var principle = HttpContext.User;
            
string userID = UserManager.GetUserId(principle);

要在您的自定義 ValidationAttribute 中獲取上下文:

var _context = (ApplicationDbContext)ValidationContext.GetService(typeof(ApplicationDbContext));

我認為如果你能更清楚地描述你的目的並分享更多相關的代碼可能會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM