我写了一个ExceptionFilter属性,我需要访问dbContext类来执行数据库事务。但我null在我的过滤器属性中收到了引用。有什么办法可以让我得到工作参考dbContext吗? public class AppExceptionAttribute : ExceptionFilterAttribute { AppIdentityDbContext _context; public AppExceptionAttribute(AppIdentityDbContext context) { _context = context; } public AppExceptionAttribute() { } public override async Task OnExceptionAsync(ExceptionContext context) { var exception = context.Exception; while (exception != null) { //here _context is null, that is a dbContext class _context.Errors.Add(new Entities.Error { Message = exception.Message, StackTrace = exception.StackTrace, Date = DateTime.Now }); exception = exception.InnerException; } await _context.SaveChangesAsync(); } }我需要提到这是一个asp.net核心应用程序
1 回答
慕标琳琳
TA贡献1830条经验 获得超9个赞
您可以IServiceProvider从ExceptionContext.
public override async Task OnExceptionAsync(ExceptionContext context)
{
var db = context.HttpContext.RequestServices.GetService<AppIdentityDbContext>();
...
await db.SaveChangesAsync();
}
- 1 回答
- 0 关注
- 183 浏览
添加回答
举报
0/150
提交
取消