我寫(xiě)了一個(gè)ExceptionFilter屬性,我需要訪問(wèn)dbContext類(lèi)來(lái)執(zhí)行數(shù)據(jù)庫(kù)事務(wù)。但我null在我的過(guò)濾器屬性中收到了引用。有什么辦法可以讓我得到工作參考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(); } }我需要提到這是一個(gè)asp.net核心應(yīng)用程序
1 回答

慕標(biāo)琳琳
TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以IServiceProvider從ExceptionContext.
public override async Task OnExceptionAsync(ExceptionContext context)
{
var db = context.HttpContext.RequestServices.GetService<AppIdentityDbContext>();
...
await db.SaveChangesAsync();
}
- 1 回答
- 0 關(guān)注
- 202 瀏覽
添加回答
舉報(bào)
0/150
提交
取消