ASP.NET Core Basic 1-1 WebHost and Project Configuration

.NET Core ASP.NET Core Basic 1-1

This section covers WebHost and project configuration

Project Profile

We can clearly find that our file contains a Json file - appsettings.json. In fact, this file is the default configuration file of our project. It contains some default settings, of course, you can add or modify it yourself. Let's not start here. We will explain how to read and manipulate configuration files later in this article.

Project Main Entrance Program

In the empty project of ASP.NET Core 2.X, you will find that there are two classes: StarUp and Program, in which the Program class is the entry (Main function) of our ASP.NET Core. Let's take a look at the Program class.

namespace ASP.NET_Core_Study
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

We can see that the Program uses a CreateWebHostBuilder function to initialize the Program, which involves our WebHost.

So what is WebHost? You can simply understand that it is the service host of our Web project, which is the core of ASP.NET Core, which calls the CreateDefaultBuilder method for creation. StartUp, which is used by generic functions, is the configuration class of our service.

Of course, you can also use WebHost.Start() for manual configuration and creation when creating a service host. Here we only study and analyze the official default methods.

First, you can see the source code of CreateDefaultBuilder(), which you can see in Github or ReSharp's decompilation function. Here I copy the source code directly from GitHub's open source code.

 /// <summary>
        /// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
        ///     use Kestrel as the web server and configure it using the application's configuration providers,
        ///     set the <see cref="IHostingEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///     load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
        ///     load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     load <see cref="IConfiguration"/> from environment variables,
        ///     load <see cref="IConfiguration"/> from supplied command line args,
        ///     configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///     and enable IIS integration.
        /// </remarks>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
        public static IWebHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new WebHostBuilder();
            if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }
            if (args != null)
            {
                builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }
            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }
                config.AddEnvironmentVariables();
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
            }).
            UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });
            ConfigureWebDefaults(builder);
            return builder;
        }

You can see very clearly here that this function will look for appsettings.json and appsettings.{env.EnvironmentName}.json. Therefore, we should not modify the file name of this file when using the default method to carry out the project actual combat. And we can see that this file is divided into two parts, one is our publish, the other is our development version. Their file names are different, and we can also find these statements in the source code. At the same time, our builder calls the UseConfiguration method, which is a parameter configuration method that receives some of the parameters we enter from the console.

In addition, we can see that he has also replaced the UseDefault Service Provider and set UseContentRoo in the root directory with the following source code

public static IWebHostBuilder UseContentRoot(this IWebHostBuilder hostBuilder, string contentRoot)
{
    if (contentRoot == null)
    throw new ArgumentNullException(nameof (contentRoot));
    return hostBuilder.UseSetting(WebHostDefaults.ContentRootKey, contentRoot);
}

public IWebHostBuilder UseSetting(string key, string value)
{
    this._config[key] = value;
    return (IWebHostBuilder) this;
}

At this point, I need to introduce two ways of starting our ASP.NET Core. One is to deploy a project using our official Microsoft IIS, which essentially injects dll into IIS services. Of course, we know that IIS is a Web server on Windows. If we want to develop cross-platform, we can use Kestrel developed by Microsoft. The source code of ConfigureWebDefaults function in the source code can see the relevant operations.

internal static void ConfigureWebDefaults(IWebHostBuilder builder)
        {
            builder.UseKestrel((builderContext, options) =>
            {
                options.Configure(builderContext.Configuration.GetSection("Kestrel"));
            })
            .ConfigureServices((hostingContext, services) =>
            {
                // Fallback
                services.PostConfigure<HostFilteringOptions>(options =>
                {
                    if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });
                // Change notification
                services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>(
                            new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));

                services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();

                services.AddRouting();
            })
            .UseIIS()
            .UseIISIntegration();
        }

We can see that here, it reads the relevant configuration from the configuration file to configure the service options we started using. The UseKestrel function registers some services for subsequent use. I'm not going to go into details here, because this section just wants you to have a preliminary understanding of the project's launch. What you need to know is that, at the current location, we found that ASP.NET Core programs will configure everything before instantiating WebHost, and we can use an open source cross-platform Web. Server Kestrel.

StartUp

StartUp class is a configuration class. It has Configure (IApplication Builder app, IHosting Environment env) and ConfigureServices(IServiceCollection services) methods. In these two methods, ConfigureServices is our service configuration method or container configuration, which is mainly used to configure our dependencies. The injected classes, and the Configure method is where we configure middleware, are two concepts that I will explain in very detail in the next two articles.

summary

This article is not a lot of content, mainly to let you know that ASP.NET Core is actually a simple console program, but it calls some services.

Overall, our ASP.NET Core WebHost creation process is

  • Configure the server UseKestrel()
  • Configure the root directory UseContentRoot()
  • Add the configuration file source ConfigureAppConfiguration ((context, builder) => builder. AddJsonFile ("appset. JSON", true, true))
  • The registration log is logged to the ConfigureLogging console (builder => builder. AddConsole ())
  • Configure StartUp class, and configure UseStartup() for dependency injection and middleware.
  • Generate WebHost, Build() returns a WebHost object
  • Running WebHost, Run() starts WebHost

Of course, the IWebHostBuilder interface also has some other common methods. Here's a simple list.

  • UseUrls, configure the boot Ip address
  • UseSetting, replacing default appsettings.json with a new file
  • UseShutdown Timeout, automatic shutdown
  • UseEnvironment, configuring the environment at startup (production Or development)

These are the functions I often use. Other functions you can learn from Microsoft's official API documents or ASP.NET Core's source code are not difficult.

Reference

Asp.netCore Running

If my article helps you, please help me with a star in the github. NET CoreGuide project and a focus and recommendation in the blog park.

Github

BiliBili Home Page

WarrenRyan'sBlog

Blog Garden

Tags: ASP.NET JSON github IIS Web Server

Posted on Tue, 27 Aug 2019 08:42:08 -0700 by recklessgeneral