当前位置:网站首页>ASP. Net startup and running mechanism

ASP. Net startup and running mechanism

2022-06-26 03:43:00 yuyue5945

ASP.NET Core

Alt

Illustration

1、Web server: ASP.NET CORE Two kinds of servers are available :kestrel and HTTP.sys

  • kestrel It's a cross platform Web The server
  • HTTP.sys Can only be used in Windows in

2、Internet : In Wan , need windows When verifying , You can choose HTTP.sys

3、IIS、Apache、Nginx: Reverse proxy

ASP .NET Core Start of

The start-up flow chart is as follows

Alt

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
  1. Main: The starting point of the program ,.Net Core Applications are essentially console applications
  2. CreateDefaultBuilder: Create and configure WebHostBuilder, First call Create­DefaultBuilder, Make a series of configurations .
  3. UseStartup: Appoint StartUp To start the configuration file . stay StartUp To do two important jobs in
    • ConfigureServices The method is to register the service
    • Configure The method is to configure the pipeline , Used to specify how to handle each http Requested , For example, we can let this program know that I use mvc To deal with it http request , It is called app.UseMvc() This method will do .
  4. BuildWebHost: Generate WebHostBuilder And after a series of configuration , adopt CreateHostBuilder(args) Object to Build a IHostBuilder.
  5. Run: call IWebHost Of Run Method to get it running .

Reverse compile into CreateDefaulBuilder Methods can see the key keywords

        public static IHostBuilder CreateDefaultBuilder(string[] args)
        {
            HostBuilder hostBuilder = new HostBuilder();
            hostBuilder.UseContentRoot(Directory.GetCurrentDirectory());
            hostBuilder.ConfigureHostConfiguration((Action<IConfigurationBuilder>)(config =>
           {
               config.AddEnvironmentVariables("DOTNET_");
               if (args == null)
                   return;
               config.AddCommandLine(args);
           }));
            hostBuilder.ConfigureAppConfiguration((Action<HostBuilderContext, IConfigurationBuilder>)((hostingContext, config) =>
           {
               IHostEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
               bool reloadOnChange = hostingContext.Configuration.GetValue<bool>("hostBuilder:reloadConfigOnChange", true);
               config.AddJsonFile("appsettings.json", true, reloadOnChange).AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", true, reloadOnChange);
               if (hostingEnvironment.IsDevelopment() && !string.IsNullOrEmpty(hostingEnvironment.ApplicationName))
               {
                   Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
                   if (assembly != (Assembly)null)
                       UserSecretsConfigurationExtensions.AddUserSecrets(config, assembly, true);
               }
               config.AddEnvironmentVariables();
               if (args == null)
                   return;
               config.AddCommandLine(args);
           })).ConfigureLogging((Action<HostBuilderContext, ILoggingBuilder>)((hostingContext, logging) =>
     {
               bool flag = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
               if (flag)
                   logging.AddFilter<EventLogLoggerProvider>((Func<LogLevel, bool>)(level => level >= LogLevel.Warning));
               logging.AddConfiguration((IConfiguration)hostingContext.Configuration.GetSection("Logging"));
               logging.AddConsole();
               logging.AddDebug();
               logging.AddEventSourceLogger();
               if (flag)
                   logging.AddEventLog();
               logging.Configure((Action<LoggerFactoryOptions>)(options => options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId | ActivityTrackingOptions.TraceId | ActivityTrackingOptions.ParentId));
           })).UseDefaultServiceProvider((Action<HostBuilderContext, ServiceProviderOptions>)((context, options) =>
     {
               bool flag = context.HostingEnvironment.IsDevelopment();
               options.ValidateScopes = flag;
               options.ValidateOnBuild = flag;
           }));
            return (IHostBuilder)hostBuilder;
        }

UseKestrel Specify the server to use Kestrel, If you use HttpSys, Need to use UseHttpSys. UseContentRoot Specify the root directory ConfigureAppConfiguration Read configuration file ConfigureLogging Configure log handler UseIISIntegration Configure the application to be in IIS Run in . If the application is not using IIS As a reverse proxy , that UseIISIntegration It won't have any effect . therefore , Even if the application is not IIS Running in the scheme , You can also safely call this method . UseDefaultServiceProvider Set the default dependency injection container .

ASP .NET Core Pipeline middleware

Request pipeline Handle http requests And back to responses That's the code that makes up request pipeline( Request pipeline ). middleware : We can use some programs to configure the request pipeline (request pipeline) To deal with requests and responses. Like processing validation (authentication) The program , MVC It's a middleware in itself (middleware).

When a request is received , The request will be handed over to the middleware pipeline composed of middleware for processing , Pipeline is composed of multiple middleware , Requests come in from one end of a middleware , Coming out of the other end of the middleware , Every middleware can be used for HttpContext Request start and end to process .

 middleware

Blogger GitHub Address

https://github.com/yuyue5945

Pay attention to the official account

 official account

原网站

版权声明
本文为[yuyue5945]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180546225388.html