Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access dbcontext inside ExceptionFilter

I've written an ExceptionFilter attribute which in that i need to access dbContext class to do database affairs. but i receive null reference in my filter attribute.

Is there any way that i can get working reference of 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();
        }
    }

i need to mention that is an asp.net core application

like image 802
Reza EN Avatar asked May 13 '26 21:05

Reza EN


1 Answers

You can access the IServiceProvider from the ExceptionContext.

public override async Task OnExceptionAsync(ExceptionContext context)
{
    var db = context.HttpContext.RequestServices.GetService<AppIdentityDbContext>();

    ...

    await db.SaveChangesAsync();
}
like image 142
Brad Avatar answered May 16 '26 10:05

Brad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!