c# - 在 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]
在我的控制器方法中有属性。有没有可能?
解决方案
与其尝试创建自己的新实例,不如在过滤器中SamuraiDbContext
使用依赖注入。为此,您需要做三件事:
VerifyProfile
使用类型参数添加构造函数SamuraiDbContext
并将其存储为字段:private readonly SamuraiDbContext dbContext; public VerifyProfile(SamuraiDbContext dbContext) { this.dbContext = dbContext; }
添加
VerifyProfile
到 DI 容器:services.AddScoped<VerifyProfile>();
用于
ServiceFilter
将过滤器连接到 DI 容器:[ServiceFilter(typeof(VerifyProfile))] public IActionResult YourAction() ...
您可以ServiceFilter
在操作级别(如图所示)或控制器级别应用该属性。您也可以在全球范围内应用它。为此,请将上面的步骤 3 替换为以下内容:
services.AddMvc(options =>
{
options.Filters.Add<VerifyProfile>();
});
作为附加资源,这篇博文很好地介绍了其他一些选项。
推荐阅读
- json - 在 PostgreSQL json 查询中选择布尔值为 true 的键
- sql - postgres 抛出的 COPY FROM 中的语法错误
- javascript - 谷歌折线图在微软边缘工作,但不在谷歌浏览器上
- java - 如何通过改造调用处理来自网络的错误
- sql - Oracle 正则表达式替换用逗号包围的字符串的多次出现
- java - 如何在 java spring boot 中使用 mongoDB 高级过滤器
- amazon-cloudformation - Cloudformation 嵌套函数 EC2 Image Builder
- rest - Swagger API 规范 请求对象设计
- xml - 读取 Vb.net 中的半结构化 Xml 文件(不同节点/子节点)
- javascript - 带有 JSON 参数的请求抛出 Uncaught (in promise) 语法错误