Created
December 4, 2018 04:38
-
-
Save vlapenkov/c39f57c834b082e93326573dcd2dfd82 to your computer and use it in GitHub Desktop.
Filters asp core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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