.NET Core 管道過濾器擴展

if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); }

驗證是否爲開發環境     是就正常報錯   不然跳轉到錯誤頁緩存

 

app.UseStaticFiles();app

驗證當前請求是否存在物理物件   存在直接返回   不走MVC路由ide

 

之前的管道模型  根據請求傳遞的控制器 方法  先實例化控制器  而後在invoke    在invoke中 執行管道中的20來個事件spa

在.NET Core中  先進入受權驗證等一系列操做   成功在實例化控制器等後續操做code

 

 

 

 

 

擴展過濾器    中間件

    都須要繼承Attribute     接口能夠選擇繼承IActionFilter  IResourceFilter  IResultFilter blog

  繼承IActionFilters的過濾器在管道中的Action Filters環節觸發 繼承

  繼承IResultFilter 的過濾器在管道中的IResultFilter 環節觸發(本身在application層寫的執行完畢後觸發)接口

  繼承ResourceFilters的過濾器其在管道的ResourceFilters環節觸發   (適合作一些短路  好比緩存  這裏存在就直接返回 )事件

 

三種過濾器執行的先後順序  ResourceFilters入→IActionFilters入→IActionFilters出→IResultFilter入→IResultFilter出→ResourceFilters出

只有ResourceFilters在數據模型綁定以前   其餘的都在數據模型綁定以後    異常處理過濾須要在進入數據模型綁定纔出發

 

這些過濾器的 context.Result就是返回的數據    進入下一環節以前  會進行驗證context.Result中的數據是否爲null   若是不爲null  就直接返回了    

 

 局部過來:在方法上直接直接加上過濾器  

 全局過濾: 往容器中添加過濾器

public IServiceProvider ConfigureServices(IServiceCollection services) { // MVC
 services.AddMvc( options => { options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName)); options.Filters.Add(typeof(CustomActionFilterAttribute)); } );

 

 依賴注入也是在IServiceCollection中實現的

 

1. 繼承IActionFilter過濾器     

public class CustomActionFilterAttribute: Attribute, IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine("ActionFilter 以前!"); //logger.Info("ActionFilter Executing!");  } public void OnActionExecuted(ActionExecutedContext context) { Console.WriteLine("ActionFilter 以後!"); //logger.Info("ActionFilter Executed!");  } }

 2.繼承ResourceFilters過濾器

public class CustomResourceFilterAttribute : Attribute, IResourceFilter { private static readonly Dictionary<string, object> _Cache = new Dictionary<string, object>(); private string _cacheKey; public void OnResourceExecuting(ResourceExecutingContext context) { _cacheKey = context.HttpContext.Request.Path.ToString(); if (_Cache.ContainsKey(_cacheKey)) { var cachedValue = _Cache[_cacheKey] as ViewResult; if (cachedValue != null) { context.Result = cachedValue; } } } public void OnResourceExecuted(ResourceExecutedContext context) { if (!String.IsNullOrEmpty(_cacheKey) &&
                !_Cache.ContainsKey(_cacheKey)) { var result = context.Result as ViewResult; if (result != null) { _Cache.Add(_cacheKey, result); } } } }

 ********************************

擴展中間件  Middleware   Map適合作一些分發    根據請求條件指定中間件

app.Map("/Jcb",MapTest)    請求到這裏就不會繼續日後面執行

app.MapWhen()   跟上面的同樣  更加靈活  可是都沒有回頭路  當前中間件就直接結束並返回

 

UseWhen()  執行裏面的後還繼續日後面執行中間件

相關文章
相關標籤/搜索