I'm trying to implement a roles / permissions system in my application, but I can't figure how to use DbContext inside m AuthorizeAttributeClass.
Here is the code that I am using :
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using HygeneApi.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace HygeneApi.Authorization
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class PrivilegeAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _privilege;
private readonly ConcreetDataContext _context;
public PrivilegeAuthorizeAttribute(string privilege)
{
_privilege = privilege;
}
public async void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
IServiceCollection serviceCollection = new ServiceCollection();
using (var contexte = new ConcreetDataContext(serviceCollection.GetService<DbContextOptions<ConcreetDataContext>>()))
{
var currentUser = await _context.Users.AsQueryable().FirstOrDefaultAsync(u => u.Email == user.Identity.Name);
Console.WriteLine(currentUser.FirstName);
}
}
}
I'm getting the error : "IServiceCollection does not contain a definition for GetService .... "
And I can't also use Microsoft.Extensions.DependencyInjection.Abstractions :
I've installed the package and everything, but I'm always having the type or namespace name Abstractions does not exist in Microsoft.Extensions.DependencyInjection.
Thank you in advance for your help !