首页 > 解决方案 > 在 ActionFilter 中间件中使用 DbContext

问题描述

我想DbContext在我的 ActionFilter 中间件中使用 a 。可能吗?

public class VerifyProfile : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        using (var context = new SamuraiDbContext())
        {
            var user = filterContext.HttpContext.User.Identity.Name;
            if (context.Profiles.SingleOrDefaultAsync(p => p.IdentityName == user).Result == null)
            {
                filterContext.Result = new RedirectResult("~/admin/setup");
            }
        }
    }
}

但是这段代码using (var context = new SamuraiDbContext())需要传递选项。我应该再次通过DbContextOptionsBuilder()这里还是有其他方式?

我想[VerifyProfile]在我的控制器方法中有属性。有没有可能?

标签: c#asp.net-coreasp.net-core-mvcasp.net-core-2.0ef-core-2.0

解决方案


与其尝试创建自己的新实例,不如在过滤器中SamuraiDbContext使用依赖注入。为此,您需要做三件事:

  1. VerifyProfile使用类型参数添加构造函数SamuraiDbContext并将其存储为字段:

    private readonly SamuraiDbContext dbContext;
    
    public VerifyProfile(SamuraiDbContext dbContext)
    {
        this.dbContext = dbContext;
    }
    
  2. 添加VerifyProfile到 DI 容器:

    services.AddScoped<VerifyProfile>();
    
  3. 用于ServiceFilter将过滤器连接到 DI 容器:

    [ServiceFilter(typeof(VerifyProfile))]
    public IActionResult YourAction()
        ...
    

您可以ServiceFilter在操作级别(如图所示)或控制器级别应用该属性。您也可以在全球范围内应用它。为此,请将上面的步骤 3 替换为以下内容:

services.AddMvc(options =>
{
    options.Filters.Add<VerifyProfile>();
});

作为附加资源,这篇博文很好地介绍了其他一些选项。


推荐阅读