aspについてNetcoreでAOPを実現する方法
10417 ワード
誰かがこれに言及したようで、ちょうど今日見ました。
mvc 5 aspより.NetcoreのAOP実現は超簡単です。
1.まず、ActionFilterAttributeから継承されたクラスを作成します.このプロパティには6つの方法が書き換えられます.次はタグです.public class DoSomething:ActionFilterAttribute
{
private readonly ILogger _logger;
public DoSomething(ILoggerFactory logger) => _logger = logger.CreateLogger(" DoSomething ");
public override void OnActionExecuted(ActionExecutedContext context)
{
_logger.LogWarning("3. ");
base.OnActionExecuted(context);
_logger.LogWarning("4. ");
}
public override void OnActionExecuting(ActionExecutingContext context)
{
_logger.LogWarning("1. ");
base.OnActionExecuting(context);
_logger.LogWarning("2. ");
}
public override void OnResultExecuted(ResultExecutedContext context)
{
_logger.LogWarning("7. ");
base.OnResultExecuted(context);
_logger.LogWarning("8. ");
}
public override void OnResultExecuting(ResultExecutingContext context)
{
_logger.LogWarning("5. ");
base.OnResultExecuting(context);
_logger.LogWarning("6. ");
}
}
2.startupに依存を追加 public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ConsoleWrite>();
services.AddScoped<DoSomething>();
services.AddScoped<ConsoleLogFilter>();
}
3.コントローラにプロパティServiceFilterを追加します.このプロパティは、Orderが小さいほど優先されます.すべてのアクションを実行したくない場合は、対応するアクションに追加できます. [ServiceFilter(typeof(ConsoleWrite),Order =2)]
[ServiceFilter(typeof(DoSomething),Order =1)]
[ServiceFilter(typeof(ConsoleLogFilter),Order =0)]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
public class DoSomething:ActionFilterAttribute
{
private readonly ILogger _logger;
public DoSomething(ILoggerFactory logger) => _logger = logger.CreateLogger(" DoSomething ");
public override void OnActionExecuted(ActionExecutedContext context)
{
_logger.LogWarning("3. ");
base.OnActionExecuted(context);
_logger.LogWarning("4. ");
}
public override void OnActionExecuting(ActionExecutingContext context)
{
_logger.LogWarning("1. ");
base.OnActionExecuting(context);
_logger.LogWarning("2. ");
}
public override void OnResultExecuted(ResultExecutedContext context)
{
_logger.LogWarning("7. ");
base.OnResultExecuted(context);
_logger.LogWarning("8. ");
}
public override void OnResultExecuting(ResultExecutingContext context)
{
_logger.LogWarning("5. ");
base.OnResultExecuting(context);
_logger.LogWarning("6. ");
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ConsoleWrite>();
services.AddScoped<DoSomething>();
services.AddScoped<ConsoleLogFilter>();
}
[ServiceFilter(typeof(ConsoleWrite),Order =2)]
[ServiceFilter(typeof(DoSomething),Order =1)]
[ServiceFilter(typeof(ConsoleLogFilter),Order =0)]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}