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() 执行里面的后还继续日后面执行中间件