我的 API 中有一个过滤器(用于身份验证),但为了检查令牌,我必须查看数据库,这并不难,但当我想通过我的 ctor 获取 DataBaseContext 时,我无法使用该过滤器不再了。请看这里:
这是过滤器类的一部分:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiAuth : Attribute, IAsyncActionFilter
{
private readonly DataBaseContext _db;
public ApiAuth(DataBaseContext db)
=> _db = db;
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
}
这是用户控制器的一部分
[Route("api/v1/[controller]")]
[ApiController]
[ApiAuth]
public class UserController : Controller
{
}
“[ApiAuth]”现在给我一个错误,它需要一个 DataBaseContext,但它无法提供它。
错误“CS7036:没有给出与“ApiAuth.ApiAuth(Databasecontext)”的形式参数“db”匹配的参数。”
我的问题是,我不知道如何获取我的上下文,你只能通过ctor获取它,还是我错了?
这里有几件事需要检查。
ConfigureServices
方法中注册了dbcontext吗?像这样
services.AddDbContext<YourDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
ConfigureServices
中将过滤器注册为IoC容器中的服务?使用此设置,您应该在过滤器中获得 dbcontext。
否则,您可以使用服务定位器模式来解析不需要构造函数注入的dbcontext。
var context = context.HttpContext.RequestServices.GetService<DataBaseContext>();
你的过滤器也应该像这样应用
[ServiceFilter(typeof(ApiAuth))]
如果您可以在过滤器中访问 httpContext (这通常是可能的) 那么你就可以做这样的事情
public override void onActionExecuted(ActionExecutedContext filtercontext)
{
var db = filterContext.HttpContext.RequestServices.GetService<ApplicationDbContext>();
}