Home > OS >  DbContext error when using it for ActionFilter in ASP.NET Core MVC
DbContext error when using it for ActionFilter in ASP.NET Core MVC

Time:01-10

I need to log certain user actions, such as Login, logout, CRUD, etc. and save to a table called AuditRecords. I have a DbContext called WebAppContext:

public class WebAppContext : DbContext
{
    public WebAppContext(DbContextOptions<WebAppContext> options)
        : base(options)
    {
    }

    public DbSet<NAW> NAW { get; set; }
    public DbSet<Audit> AuditRecords { get; set; }
}

I have learned that applying an ActionFilter and decorate a controller with it is the way to go. The WebAppContext is causing a red squiggly asking for the 'options', which baffles me. I have tried DI, but got the same results. Any thoughts? I am on DotNet 6.01.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    // CS7036: There is no argument given that corresponds to the formal 
    // parameter 'options' of 'WebAppContext(DbContext<WebAppContext>)'
    using (WebAppContext _context = new WebAppContext())  
    {
        Audit audit = new Audit()
            {
                AuditId = Guid.NewGuid(),
                UserName = (filterContext.HttpContext.User.Identity.IsAuthenticated) ? filterContext.HttpContext.User.Identity.Name : "Anonymous",
                IPAddress = filterContext.HttpContext.Connection.RemoteIpAddress.ToString(),
                AreaAccessed = filterContext.HttpContext.Request.Path,
                Timestamp = DateTime.UtcNow
            };

        _context.AuditRecords.Add(audit);
        _context.SaveChanges();
    } 

    base.OnActionExecuting (filterContext); 
}

CodePudding user response:

WebAppContext expects a DbContext<WebAppContext> to be passed into its constructor . However , you are calling the constructor without providing anything :

WebAppContext _context = new WebAppContext()

To fix the issue , you can just plug into the Dependency Injection system that you've set up

public class CustomFilter : IActionFilter
    {
        private readonly WebAppContext _context;
        public CustomFilter(WebAppContext context)
        {
            _context = context;
        }
      
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //.......
                
            _context.AuditRecords.Add(...);
            _context.SaveChanges();
        }
    }

CodePudding user response:

First, add the Nuget package Microsoft.EntityFrameworkCore.SqlServer to your project. Then, add the following code to the ConfigureServices method of your Startup class:

services.AddDbContext<WebAppContext>(options =>
 options.UseSqlServer("[your connectionstring here]"));

That's the bare minimum and this will enable you to inject the DbContext into the ActionFilter.

  •  Tags:  
  • Related