专业提供网站制作,企业网站备案备注,欧美普货专线是快递吗,wordpress中文是什么?概述通过使用 ASP.NET Core 中的筛选器#xff0c;可在请求处理管道中的特定阶段之前或之后运行代码。内置筛选器处理任务#xff0c;例如#xff1a;授权#xff08;防止用户访问未获授权的资源#xff09;。响应缓存#xff08;对请求管道进行短路出路#xff0c;以便… 概述通过使用 ASP.NET Core 中的筛选器可在请求处理管道中的特定阶段之前或之后运行代码。内置筛选器处理任务例如授权防止用户访问未获授权的资源。响应缓存对请求管道进行短路出路以便返回缓存的响应。可以创建自定义筛选器用于处理横切关注点。 横切关注点的示例包括错误处理、缓存、配置、授权和日志记录。 筛选器可以避免复制代码。 例如错误处理异常筛选器可以合并错误处理。ASP.NET Core Filter如何支持依赖注入?可以通过全局注册支持依赖注入。通过TypeFilter(typeof(Filter)) 标记在方法标记在控制器。通过ServiceType(typeof(Filter))标记在方法标记在控制器必须要注册Filter这类TypeFilter和ServiceType的本质是实现了一个IFilterFactory接口代码实现1、普通Filter使用继承: Attribute, IActionFilter。 public class TestActionFilterAttribute : Attribute, IActionFilter{public void OnActionExecuted(ActionExecutedContext context){if (context.HttpContext.Request.Query.TryGetValue(id, out StringValues value)){Console.WriteLine(value.First());}else{context.HttpContext.Response.Redirect(/Error/404);}}public void OnActionExecuting(ActionExecutingContext context){ }}[TestActionFilter]public IActionResult Index(){return View();}
2、使用 [TypeFilter(typeof(TestActionFilterAttribute))]注入。 public class TestActionFilterAttribute : Attribute, IActionFilter{private readonly ILogger _logger;public TestActionFilterAttribute(ILoggerFactory logger){_logger logger.CreateLogger(TestActionFilterAttribute);}public void OnActionExecuted(ActionExecutedContext context){_logger.LogDebug($11111);if (context.HttpContext.Request.Query.TryGetValue(id, out StringValues value)){Console.WriteLine(value.First());}else{context.HttpContext.Response.Redirect(/Error/404);}}public void OnActionExecuting(ActionExecutingContext context){ }}[TypeFilter(typeof(TestActionFilterAttribute))]public IActionResult Index(){return View();}3、使用 [ServiceFilter(typeof(TestActionFilterAttribute))]注入。 [ServiceFilter(typeof(TestActionFilterAttribute))]public IActionResult Index(){return View();}
运行测试发现报错于是ConfigureServices加上services.AddSingletonTestActionFilterAttribute(); // This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddSingletonTestActionFilterAttribute();services.AddControllersWithViews();}
运行测试成功。4、通过全局注册 public void ConfigureServices(IServiceCollection services){// services.AddSingletonTestActionFilterAttribute();services.AddControllersWithViews(options {// 添加全局异常options.Filters.AddTestActionFilterAttribute();});}
代码地址https://gitee.com/conanOpenSource_admin/service-filter_-type-filter