当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core 系列 16 Web主机 IWebHostBuilder

asp.net core 系列 16 Web主机 IWebHostBuilder

2019年01月26日  | 移动技术网IT编程  | 我要评论

yy刘大美人真实身份,庾澄庆家世,梦幻金庸群侠传v2.4

一.概述

         在asp.net core中,host主机负责应用程序启动和生存期管理。host主机包括web 主机(iwebhostbuilder)和通用主机(ihostbuilder)。web 主机是适用于托管 web 应用;通用主机(asp.net core 2.1 或更高版本)是适用于托管非 web 应用;在未来的版本中,通用主机将适用于托管任何类型的应用,包括 web 应用。 通用主机最终将取代 web 主机。本篇先来了解asp.net core web主机。

  

  1.1 设置web主机以及执行的任务

    创建使用 iwebhostbuilder 实例的主机。 通常在应用的入口点 main 方法中执行。 在项目模板中,main 位于 program.cs。

         public static iwebhostbuilder createwebhostbuilder(string[] args) =>
            webhost.createdefaultbuilder(args)
                .usestartup<startup>();

    下面详细说下createdefaultbuilder 执行的下列任务:

    (1) 将内置的 kestrel 服务器配置为 web 服务器。

    (2) 设置content root 内容根路径,并由 directory.getcurrentdirectory 返回的路径。

    (3) 通过以下加载主机配置:

      前缀为 aspnetcore_ 的环境变量(例如,aspnetcore_environment)。

      命令行参数。

    (4) 按以下顺序加载应用配置

      appsettings.json。

                     appsettings.{environment}.json。

                     应用在使用入口程序集的 development 环境中运行时的机密管理器。

                     环境变量。

                     命令行参数。

    (5) 设置console and debug 输出的日志记录。在 appsettings.json 或 appsettings.{environment}.json 文件的日志记录配置部分(logging)中指定的日志筛选规则。

    (6)  asp.net core 模块使用iis托管运行时,createdefaultbuilder 会启用 iis 集成,这会配置应用的基址和端口。 iis 集成还配置应用以捕获启动错误。

    (7) 如果应用环境为“开发”,请将 serviceprovideroptions.validatescopes 设为 true。

 

  1.2 web主机的扩展配置

     iwebhostbuilder下的configureappconfiguration、configurelogging 以及其他方法可重写(第三大点讲)和增强 createdefaultbuilder 定义的配置。 下面是一些示例:

    (1) configureappconfiguration 

      configureappconfiguratio用于指定应用的 iconfiguration。下面的 configureappconfiguration 调用添加委托,以在 appsettings.xml 文件中添加应用配置。 可多次调用 configureappconfiguration。具体参照 ”asp.net core 系列 10 配置configuration“ 。

      webhost.createdefaultbuilder(args)
      .configureappconfiguration((hostingcontext, config) =>
      {
          config.addxmlfile("appsettings.xml", optional: true, reloadonchange: true);
      })

    (2) configurelogging

      configurelogging调用添加委托,以将最小日志记录级别 (setminimumlevel) 配置为 loglevel.warning。 此设置重写 createdefaultbuilder 在 appsettings.development.json 和 appsettings.production.json 中配置的设置,分别为 loglevel.debug 和 loglevel.error。 可多次调用 configurelogging。具体参照 “asp.net core 系列 13 日志”。

      webhost.createdefaultbuilder(args)
      .configurelogging(logging => 
      {
          logging.setminimumlevel(loglevel.warning);
      })

    (3) configurekestrel

      下面调用 configurekestrel 来重写 createdefaultbuilder 在配置 kestrel 时默认的 30,000,000 字节,大约为28.6mb。maxrequestbodysize是获取或设置任何请求主体的最大允许大小(以字节为单位)。设置为null时,最大请求正文大小不受限制。

      webhost.createdefaultbuilder(args)
      .configurekestrel((context, options) =>
      {
          options.limits.maxrequestbodysize = 20000000;
      });

 

二.主机配置值

  webhostbuilder 依赖于以下的方法设置主机配置值:

     (1)主机生成器配置,其中包括格式 aspnetcore_{configurationkey} 的环境变量。 例如 aspnetcore_environment。

    (2)usecontentroot 和 useconfiguration 等扩展。

    (3)usesetting 和关联键。 使用 usesetting 设置值时,该值设置为无论何种类型的字符串。

  2.1  application key (name)

    在主机构造期间调用 usestartup 或 configure 时,会自动设置 ihostingenvironment.applicationname 属性。 该默认值设置为应用入口点的程序集的名称。 要显式设置值,请使用 webhostdefaults.applicationkey。环境变量:aspnetcore_applicationname

      public void configure(iapplicationbuilder app, ihostingenvironment env)
        {
            //应用程序默认名称为:mynetcorestudy (也就是项目名称)
            string s = env.applicationname;
            //..
     //显示设置
     webhost.createdefaultbuilder(args)   .usesetting(webhostdefaults.applicationkey, "customapplicationname")

  2.2捕获启动错误

    启动错误的捕获。 默认为 false, 启动期间出错,主机退出。当 true 时,主机在启动期间捕获异常并尝试启动服务器。当程序使用 kestrel 在 iis 后方运行,默认值是 true。环境变量:aspnetcore_capturestartuperrors

      webhost.createdefaultbuilder(args)
      .capturestartuperrors(true)

  2.3 内容根

    设置确定web根目录的基路径。用于搜索的内容文件,比如mvc的视图。默认为应用程序集所在的文件夹。环境变量:aspnetcore_contentroot。

        webhost.createdefaultbuilder(args)
        .usecontentroot("c:\\<content-root>")

  2.4 详细错误  

    确定是否应捕获详细错误。默认值:false。启用为true时,会捕获详细的异常。或当环境设置为 development时也会捕获详细的异常。 环境变量 aspnetcore_detailederrors

    webhost.createdefaultbuilder(args)
        .usesetting(webhostdefaults.detailederrorskey, "true")

  2.5 环境  

    设置应用的环境。默认值:production。 使用 visual studio 时,可能会在 launchsettings.json 文件中设置环境变量。环境变量:aspnetcore_environment

        webhost.createdefaultbuilder(args)
    .useenvironment(environmentname.development)

  2.6 https 端口

    设置 https 重定向端口。 用于强制实施 https。 环境变量:aspnetcore_https_port。

      webhost.createdefaultbuilder(args)
        .usesetting("https_port", "8080")

  2.7 服务器 (kestrel) url

    指示 ip 地址或主机地址,host启动时侦听。默认: http://localhost:5000。设置为服务器响应的以分号分隔 (;) 的 url 前缀列表。环境变量:aspnetcore_urls

    webhost.createdefaultbuilder(args)
      .useurls("http://www.lhsxpumps.com/_*:5000;http://localhost:5001;https://hostname:5002")

 

三.重写(覆盖)配置

         配置可用于配置 web 主机。 在下面的示例中,主机配置是根据需要在 hostsettings.json 文件中指定。 命令行参数可能会重写从 hostsettings.json 文件加载的任何配置。 生成的配置(在 config 中)用于通过 useconfiguration 配置主机。 iwebhostbuilder 配置会添加到应用配置中。

   hostsettings.json  { urls: "http://*:5005" }
        public static iwebhostbuilder createwebhostbuilder(string[] args)
        {
            //iconfiguration的配置主机
            var config = new configurationbuilder()
                .setbasepath(directory.getcurrentdirectory())
                //主机配置在hostsettings.json 文件中指定
                .addjsonfile("hostsettings.json", optional: true)
                // 命令行参数可能会重写从 hostsettings.json 文件加载的任何配置
                .addcommandline(args)
                .build();

            return webhost.createdefaultbuilder(args)
                .useurls("http://*:5000")
                //config重写useurls
                .useconfiguration(config)
                .configure(handle1);
        }

        private static void handle1(iapplicationbuilder app)
        {
            app.run(async context =>
           {
               await context.response.writeasync("handle1 test 1");
           });
        }

  如果在执行 dotnet 运行时从命令提示符传入。 命令行参数,重写 hostsettings.json 文件中的 urls 值,且服务器侦听端口 8080。

  dotnet run --urls "http://*:8080"

    启动时,url参数重写的的关系是:useurls被hostsettings.json重写, hostsettings.json又被命令行参数重写。

 

四 .管理主机

         对于启动主机有二种方式:run和start。使用run 方法启动 web 应用是阻止调用线程,直到显示关闭主机。使用start方法是非阻止方式运行主机。具体用法请查看官网。

    // runs a web application and block the calling thread until host shutdown.
    createwebhostbuilder(args).build().run();
     createwebhostbuilder(args).build().start();
     //非阻止方式,所有必须加上readline,
     console.readline();

 

五. ihostingenvironment 接口

  ihostingenvironment 接口提供有关应用的 web 承载环境的信息,默认是将 ihostingenvironment 注入到 startup构造函数,在configure方法中引用。下面使用构造函数注入获取 ihostingenvironment 以使用其属性和扩展方法:

public class customfilereader
{
    private readonly ihostingenvironment _env;

    public customfilereader(ihostingenvironment env)
    {
        _env = env;
    }

    public string readfile(string filepath)
    {
        //返回ifileprovider,指向 webrootpath
        var fileprovider = _env.webrootfileprovider;
        // process the file here
    }
}

   创建自定义中间件时可以将 ihostingenvironment 注入 invoke 方法(参考asp.net core 系列 15 中间件):

public async task invoke(httpcontext context, ihostingenvironment env)
{
    if (env.isdevelopment())
    {
        // configure middleware for development
    }
    else
    {
        // configure middleware for staging/production
    }

    var contentrootpath = env.contentrootpath;
}

 

六.iapplicationlifetime 接口

         iapplicationlifetime 用于应用程序在启动和关闭时的活动。 接口上的三个属性是用于注册 action 方法。用于定义启动和关闭事件标记。

public class startup
{
    public void configure(iapplicationbuilder app, iapplicationlifetime applifetime)
    {
        applifetime.applicationstarted.register(onstarted);
        applifetime.applicationstopping.register(onstopping);
        applifetime.applicationstopped.register(onstopped);

        console.cancelkeypress += (sender, eventargs) =>
        {
            applifetime.stopapplication();
            // don't terminate the process immediately, wait for the main thread to exit gracefully.
            eventargs.cancel = true;
        };
    }

    private void onstarted()
    {
        // perform post-startup activities here
    }

    private void onstopping()
    {
        // perform on-stopping activities here
    }

    private void onstopped()
    {
        // perform post-stopped activities here
    }
}

 

七. 作用域验证

  如果应用环境为“开发”,则 createdefaultbuilder 将 serviceprovideroptions.validatescopes 设为 true。若将 validatescopes 设为 true,默认服务提供程序会执行检查来验证以下内容:

         作用域服务不能直接或间接地从根服务提供者解析。

         作用域服务不会直接或间接地注入到单例中(服务的生存期)。

  webhost.createdefaultbuilder(args)
      .usedefaultserviceprovider((context, options) => {
          options.validatescopes = true;
      })

  当true将执行检查,验证作用域服务,永远不会从根提供程序解析(不从顶级容器中获取scoped生命周期服务,所有服务都是注入到容器中iservicecollection)。 mark:没有完全理解,以后再说。

 

 参考文献:

    官方文档:asp.net core web主机

   

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网