ASP.NET Core 中的应用程序启动 Startup

 
ASP.NET Core 应用使用Startup类来作为启动类。
 
  Startup类中包含了ConfigureServices方法,Configure方法,IConfiguration,IHostingEnvironment,IServiceCollection,Startup 筛选器
 
  1.  IConfiguration  用于获取配置文件
Configuration.GetConnectionString("MovieContext")

  2. IHostingEnvironment 获取项目环境变量

 public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            HostingEnvironment = env;
        }
        public IHostingEnvironment HostingEnvironment { get; }
        public IConfiguration Configuration { get; }
 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var contentRootPath = HostingEnvironment.ContentRootPath;
            var applicationName = HostingEnvironment.ApplicationName;
            services.AddMvc();
        }

  3. IServiceCollection 是 DependencyInjection 的一个接口,它NET Core 内置的 依赖注入服务,用于注册服务。

   来自using Microsoft.Extensions.DependencyInjection; 命名空间。

  // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        { 
            //注册MovieContext访问上下文类,这样可以在控制器中使用构造函数方式注入使用
            services.AddDbContext<MovieContext>(options =>
      options.UseMySQL(Configuration.GetConnectionString("MovieContext")));
            services.AddTransient<IStartupFilter, RequestSetOptionsStartupFilter>();
            services.AddMvc(); 
        }

  4. ConfigureServices 方法就是用于注册服务的,如上面代码 

    • 可选。
    • 在 Configure 方法配置应用服务之前,由 Web 主机调用。
    • 其中按常规设置配置选项。
  将服务添加到服务容器,使其在应用和 Configure 方法中可用。 这些服务通过依赖关系注入或 IApplicationBuilder.ApplicationServices 解析。
 

  5. Configure 方法 

    Configure 方法用于指定应用响应 HTTP 请求的方式。 
    可通过将中间件组件添加到 IApplicationBuilder 实例来配置请求管道。 
    Configure 方法可使用 IApplicationBuilder,但未在服务容器中注册。
      承载创建 IApplicationBuilder 并将其直接传递给 Configure 。
    ASP.NET Core 模板配置支持开发人员异常页、BrowserLink、错误页、静态文件和 ASP.NET MVC 的管道,路由
  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

 

  6. Startup 筛选器
    
    在应用的 Configure 中间件管道的开头或末尾使用 IStartupFilter 来配置中间件。 IStartupFilter 有助于确保中间件在应用请求处理管道的开始或结束时由库添加的中间件之前或之后运行。
    IStartupFilter 实现单个方法(即 Configure),该方法接收并返回 Action<IApplicationBuilder>。 IApplicationBuilder 定义用于配置应用请求管道的类。 有关详细信息,请参阅使用 IApplicationBuilder 创建中间件管道。
    在请求管道中,每个 IStartupFilter 实现一个或多个中间件。 筛选器按照添加到服务容器的顺序调用。 筛选器可在将控件传递给下一个筛选器之前或之后添加中间件,从而附加到应用管道的开头或末尾。
  
  
 public class AppOptions
    {
        public string Option { get; set; } = "Option Default Value";
    }

 

    public class RequestSetOptionsMiddleware
    {
        private readonly RequestDelegate _next;
        private IOptions<AppOptions> _injectedOptions;

        public RequestSetOptionsMiddleware(
            RequestDelegate next, IOptions<AppOptions> injectedOptions)
        {
            _next = next;
            _injectedOptions = injectedOptions;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            Console.WriteLine("RequestSetOptionsMiddleware.Invoke");

            var option = httpContext.Request.Query["option"];

            if (!string.IsNullOrWhiteSpace(option))
            {
                _injectedOptions.Value.Option = WebUtility.HtmlEncode(option);
            }

            await _next(httpContext);
        }
    }
  public class RequestSetOptionsStartupFilter : IStartupFilter
    {
        public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
        {
            return builder =>
            {
                builder.UseMiddleware<RequestSetOptionsMiddleware>();
                next(builder);
            };
        }
    }

 

注册:
  // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {  
            services.AddTransient<IStartupFilter, RequestSetOptionsStartupFilter>();
            services.AddMvc();  
        }

 

当提供 option 的查询字符串参数时,中间件在 MVC 中间件呈现响应之前处理分配值:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2018-03-29 16:08  dragon.net  阅读(1270)  评论(1编辑  收藏  举报