简体   繁体   English

如何在 .net core 模型中访问当前用户和数据库上下文

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

I have a model with a method and I want to get the current UserID and have access to the database context.我有一个带有方法的模型,我想获取当前的 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)));
    }
}   

But it doesn't work :(但它不起作用:(

Can you tell me how I can do this.你能告诉我我该怎么做吗?

Thanks谢谢

Here's my error messages这是我的错误信息

I can't have access to the User property of the HttpContext Class我无法访问 HttpContext 类的 User 属性

I can't access to ValidationContext.GetService我无法访问 ValidationContext.GetService

I think you were passing wrong parameter:我认为您传递了错误的参数: 在此处输入图像描述 To Get UserId you could try:要获取 UserId,您可以尝试:

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

To get context in your custom ValidationAttribute:要在您的自定义 ValidationAttribute 中获取上下文:

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

I think it may help if you could describe your purpose more clearly and share more codes related我认为如果你能更清楚地描述你的目的并分享更多相关的代码可能会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM