Reputation: 3740
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
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:
await
for the DB operation, and avoid blocking request thread. Again, exactly for this reason you would implement an async
action.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