Skip to content

Instantly share code, notes, and snippets.

@vlapenkov
Created December 4, 2018 04:38
Show Gist options
  • Save vlapenkov/c39f57c834b082e93326573dcd2dfd82 to your computer and use it in GitHub Desktop.
Save vlapenkov/c39f57c834b082e93326573dcd2dfd82 to your computer and use it in GitHub Desktop.
Filters asp core
/// <summary>
/// Такой аттрибут надо явно регистрировать в контейнере зависимостей
/// синтаксис использования [ServiceFilter(typeof(SomeActionFilter))]
/// </summary>
public class SomeActionFilter: ActionFilterAttribute
{
private ApplicationDbContext _appDbContext;
public SomeActionFilter(ApplicationDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var firstPerson = _appDbContext.Persons.FirstOrDefault();
}
}
/// <summary>
/// Такой аттриьут не надо явно регистрировать, и использовать просто [SampleActionFilter]
/// но он не принимает параметров в контрукторе кроме зависимостей, т.е. внутри приватного класса нельзя узнать Limit родительского
/// </summary>
public class SampleActionFilterAttribute : TypeFilterAttribute
{
public int Limit { get; private set; }
public SampleActionFilterAttribute(int limit) : base(typeof(SampleActionFilterImpl))
{
Limit = limit;
}
private class SampleActionFilterImpl : ActionFilterAttribute
{
private ApplicationDbContext _appDbContext;
public SampleActionFilterImpl(ApplicationDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var firstPerson = _appDbContext.Persons.FirstOrDefault();
await next();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment