kkost
kkost

Reputation: 3740

Working with the database inside Filter attribute

I am working on a filter attribute in my ASP.NET Core Web application which will validate input model parameters. I need to compare some input parameters with some another value from SQL DB. Is that good practice to open DB connection inside filters?

Upvotes: 1

Views: 670

Answers (1)

felix-b
felix-b

Reputation: 8498

Filter attributes are good for capturing cross-cutting concerns, across multiple action methods and/or controllers. If this is your case, then using filter attributes is a good way to go.

Actually, filters are just another step in request handling pipeline, exactly like the step that invokes an action method. So basically, under the hood, it makes no difference whether you perform validation in a filter or in the action method.

A couple of considerations:

  • Implement an asynchronous filter. In this way, you can await for the DB operation, and avoid blocking request thread. Again, exactly for this reason you would implement an async action.
  • Whatever technology you use for accessing the DB, make sure it uses connection pooling. So that you don't actually open a database connection on every request, but use a ready connection from the pool.

An example of async filter, quoted from Microsoft Docs on ASP.NET Core filters

public class SampleAsyncActionFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next)
    {
        // do something before the action executes
        var resultContext = await next();
        // do something after the action executes; resultContext.Result will be set
    }
}

See also links in this answer: https://stackoverflow.com/a/40718992/4544845

Upvotes: 1

Related Questions