当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core 系列 2 启动Startup类介绍

asp.net core 系列 2 启动Startup类介绍

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

软文案例,狼局长18摸,时尚俏妈咪

一.startup类

  asp.net core 应用是一个控制台应用,它在其 program.main 方法中创建 web 服务器。其中main方法是应用的托管入口点,main 方法调用 webhost.createdefaultbuilder来创建 web 主机,自动分配了 kestrel web 服务器。iwebhostbuilder 的 build 方法生成 iwebhost对象调用run 方法启动webhost,此时托管应用并开始侦听 http 请求。代码如下所示:

public class program
    {
        public static void main(string[] args)
        {
            createwebhostbuilder(args).build().run();
        }

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

 

  1.1 应用启动 startup类

    iwebhostbuilder类的usestartup调用启动类,按照约定命名为 startup,该类必须是公共类,用于定义请求处理管道配置应用所需的任何服务。当应用启动时会调用 configureservices 和 configure两个方法。configureservices 用于注入服务, configure用于响应http请求。

public class startup
{
    // use this method to add services to the container.
    public void configureservices(iservicecollection services)
    {
        ...
    }

    // use this method to configure the http request pipeline.
    public void configure(iapplicationbuilder app)
    {
        ...
    }
}

  

  1.2  configureservices方法

    configureservices 方法负责注入服务。该方法在webhost的configure方法之前被调用,将服务添加到服务容器使得它们可以通过依赖注入在应用程序中使用,在webhost启动之前会加载该方法中的服务。典型模式是调用add{service}方法注入服务,然后调用所有 services.configure{service} 方法。注入服务后,使其在应用和 configure 方法中使用服务。在参数iservicecollection (服务容器)上有 add[service] 扩展方法,用于添加自带的framework框架服务(例如添加ef,identity,mvc服务)也可以在iservicecollection上注入自定义服务。

  public void configureservices(iservicecollection services)
        {
            //注入 razor pages 和 mvc 需要的服务
            services.addmvc();
        }

 

  1.3 configure方法

    configure方法用于指定应用响应 http 请求的方式。可将中间件注册到iapplicationbuilder 实例来配置请求管道。下面示例注册的中间件包括: exceptionhandler异常/错误处理、httpsredirection重定向、staticfiles静态文件服务器、cookiepolicy策略实施、mvc等中间件。每一个use开头的扩展方法将一个中间件添加到iapplicationbuilder请求管道中。

public void configure(iapplicationbuilder app, ihostingenvironment env)
        {
            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
            }
            else
            {
                app.useexceptionhandler("/error");
                app.usehsts();
            }

            app.usehttpsredirection();
            app.usestaticfiles();
            app.usecookiepolicy();

            app.usemvc();
        }

 

  总结: (1) program的main方法用于创建webhost服务,调用启动类startup。

      (2) startup中的configureservices方法用于将服务注入到 iservicecollection 服务容器中。

      (3) startup中的configure方法用于应用响应 http 请求,将中间件注册到 applicationbuilder中来配置请求管道。

 参考文献:

    

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

相关文章:

验证码:
移动技术网