Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure and manage Web hosts by ASP.NET Core

2025-03-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to configure and manage Web hosts with ASP.NET Core". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to configure and manage Web hosts with ASP.NET Core.

1. Preface

The ASP.NET Core application can configure and start the host (Host). The host is responsible for application startup and lifecycle management, configuring the server and request processing pipeline. The host can also set up logging, dependency injection, and configuration. The Host host includes Web host (IWebHostBuilder) and general host (IHostBuilder). This section mainly introduces the Web hosts used to host Web applications. For other types of applications, use a generic host.

two。 Set up the host

Create a host that uses an IWebHostBuilder instance. The Main method is usually executed at the entry point of the application. In the project template, Main is located in Program.cs. A typical application calls CreateDefaultBuilder by default to start creating a host:

Public class Program {public static void Main (string [] args) {CreateWebHostBuilder (args). Build (). Run ();} public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .UseStartup ();} 2.1 perform the following tasks

The code that calls CreateDefaultBuilder is in a method called CreateWebHostBuilder, which distinguishes it from the code in Main that calls Run on the generator object. CreateDefaultBuilder performs the following tasks:

● uses the application's managed configuration provider application to configure the Kestrel server as a Web server.

● sets the content root to the path returned by Directory.GetCurrentDirectory.

● loads the host configuration through the following objects:

An environment variable with a ○ prefix of ASPNETCORE_ (for example, ASPNETCORE_ENVIRONMENT).

○ command line arguments.

● loads the application configuration in the following order:

○ appsettings.json .

○ appsettings. {Environment} .json .

○ applies the secret manager that runs in a Development environment that uses portal assemblies.

○ environment variable.

○ command line arguments.

Logging of ● configuration console and debug output. Logging contains the log filtering rules specified in the logging configuration section of the appsettings.json or appsettings. {Environment} .json file.

When ● runs behind IIS using the ASP.NET Core module, CreateDefaultBuilder enables IIS integration, which configures the base address and port of the application. IIS integration also configures the application to catch startup errors.

● if the application environment is Development, set ServiceProviderOptions.ValidateScopes to true.

2.2 rewrite and enhance the defined configuration

ConfigureAppConfiguration, ConfigureLogging, and other methods and extensions of IWebHostBuilder can override and enhance the configuration defined by CreateDefaultBuilder. Here are some examples:

● ConfigureAppConfiguration: other IConfiguration used to specify the application. The following ConfigureAppConfiguration call adds a delegate to add the application configuration to the appsettings.xml file, which is demonstrated in Chapter 11 of the Core series. ConfigureAppConfiguration can be called multiple times. Note that this configuration does not apply to hosts (for example, server URL or environment).

Public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .Configuration (hostingContext, config) = > {config.AddXmlFile ("appsettings.xml", optional: true, reloadOnChange: true);})

The ● ConfigureLogging:ConfigureLogging call adds a delegate and configures the minimum logging level (SetMinimumLevel) to LogLevel.Warning. This setting overrides the CreateDefaultBuilder configuration in appsettings.Development.json and appsettings.Production.json, which are LogLevel.Debug and LogLevel.Error, respectively. ConfigureLogging can be called multiple times.

Public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .ConfigureLogging (logging = > {logging.SetMinimumLevel (LogLevel.Warning);})

● ConfigureKestrel: call ConfigureKestrel to override the 30000000-byte default Limits.MaxRequestBodySize established by CreateDefaultBuilder when configuring Kestrel:

Public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .ConfigureKestrel ((context, options) = > {options.Limits.MaxRequestBodySize = 20000000;})

When you set up a host, you can provide configuration and ConfigureServices methods. If you specify the Startup class, you must define the Configure method.

3. Host configuration valu

WebHostBuilder relies on the following methods to set host configuration values:

● host generator configuration, which includes environment variables in the format ASPNETCORE_ {configurationKey}. For example, ASPNETCORE_ENVIRONMENT.

Extensions such as ● UseContentRoot and UseConfiguration.

● UseSetting and associated keys. When you set a value using UseSetting, the value is set to a string of any type.

3.1 Application key (name)

The IHostingEnvironment.ApplicationName property is automatically set when UseStartup or Configure is called during host construction. This value is set to the name of the assembly that contains the application entry point. To set the value explicitly, use WebHostDefaults.ApplicationKey (environment variable: ASPNETCORE_APPLICATIONNAME):

Public void Configure (IApplicationBuilder app, IHostingEnvironment env) {/ / the default name of the application is: CoreWeb (that is, project name) string an = env.ApplicationName;.} public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args). UseStartup () .UseSetting (WebHostDefaults.ApplicationKey, "CoreWeb"); 3.2 catch startup errors

This setting controls the capture of startup errors. When false, an error during startup caused the host to exit. When true occurs, the host catches an exception during startup and attempts to start the server (environment variable: ASPNETCORE_CAPTURESTARTUPERRORS).

WebHost.CreateDefaultBuilder (args) .CaptureStartupErrors (true) 3.3 content root

This setting determines that ASP.NET Core starts searching for content files, such as MVC views. The content root is also used as the base path for the Web root setting. If the path does not exist, the host will fail to boot (environment variable: ASPNETCORE_CONTENTROOT).

WebHost.CreateDefaultBuilder (args) .UseContentRoot ("c:\") 3.4 detailed error

Determine whether detailed errors should be caught. When enabled (or when the environment is set to Development), the application catches detailed exceptions (environment variable: ASPNETCORE_DETAILEDERRORS).

WebHost.CreateDefaultBuilder (args) .UseSetting (WebHostDefaults.DetailedErrorsKey, "true") 3.5 environment

Set up the environment for the application. The environment can be set to any value. The values defined by the framework include Development, Staging, and Production. The value is case-insensitive. By default, the environment is read from the ASPNETCORE_ENVIRONMENT environment variable. When using Visual Studio, environment variables may be set in the launchSettings.json file. For more information about the environment, you can go to Chapter 10 of the Core series (environment variable: ASPNETCORE_ENVIRONMENT).

WebHost.CreateDefaultBuilder (args) .UseEnvironment (EnvironmentName.Development) 3.6HTTPS port

Sets the HTTPS redirect port. Used to enforce HTTPS (environment variable: ASPNETCORE_HTTPS_PORT).

WebHost.CreateDefaultBuilder (args) .UseSetting ("https_port", "8080") 3.7Server (Kestrel) URL

Indicates the IP address or host address that contains the ports and protocols that the server should listen on for requests. Set to a semicolon-delimited list of URL prefixes that the server should respond to. For example, http://localhost:123. Use "*" to indicate the IP address or hostname of a specific port and protocol (such as http://*:5000) that the server should listen on for requests. The protocol (http:// or https://) must contain each URL. Different servers support different formats (environment variable: ASPNETCORE_URLS).

WebHost.CreateDefaultBuilder (args) .UseUrls ("https://*:5000;https://localhost:5001;https://hostname:5002")

4. Rewrite configuration

Use the configuration to configure the Web host. In the following example, the host configuration is specified in the hostsettings.json file as needed. Command line arguments may override any configuration loaded from the hostsettings.json file. The resulting configuration (in config) is used to configure the host through UseConfiguration.

Create a new hostsettings.json file with the following contents:

{"urls": "https://*:5005"}public static IWebHostBuilder CreateWebHostBuilder (string [] args) {/ / IConfigurationBuilder configuration host var config = new ConfigurationBuilder () .SetBasePath (Directory.GetCurrentDirectory ()) / / Host configuration specifies .AddJsonFile (" hostsettings.json ") in the hostsettings.json file Optional: true) / / Command line arguments entered may override any configuration .AddCommandLine (args) .build () loaded from the hostsettings.json file. Return WebHost.CreateDefaultBuilder (args) .UseUrls ("https://*:5001") .UseConfiguration (config) .configure (app = > {/ / generated configuration delegate function app.Run (context = > context.Response.WriteAsync (" Hello, World! ");});})

The above code description means that if you want to specify a host running on a specific URL, the required values can be passed in from the command prompt when the dotnet runtime is executed. The command line argument overrides the urls value in the hostsettings.json file, and the server listens on port 8080:

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

When the host starts, first rewrite the urls parameter configuration provided by UseUrls with hostsettings.json config, and then rewrite the urls parameter configuration of hostsettings.json config with the command line parameter config.

5. Manage hosts

There are two ways to start the management host: Run and Start. The Run method starts the Web application and blocks the calling thread until the host is shut down. The Start method runs the host in a non-blocking manner by calling itself.

/ / RunCreateWebHostBuilder (args). Build (). Run (); / / Start: non-blocking method, all must add ReadLineCreateWebHostBuilder (args). Build (). Start (); Console.ReadLine (); 6.IHostingEnvironment interface

The IHostingEnvironment interface provides information about the Web hosting environment of the application. Use constructor injection to get IHostingEnvironment to use its properties and extension methods:

/ / example 1:public class CustomFileReader {private readonly IHostingEnvironment _ env; public CustomFileReader (IHostingEnvironment env) {_ env = env;} public string ReadFile (string filePath) {var fileProvider = _ env.WebRootFileProvider; / / Process the file here}}

Can be used to configure the application based on the environment at startup or to inject IHostingEnvironment into the Startup constructor for ConfigureServices:

/ example 2:public class Startup {public Startup (IHostingEnvironment env) {HostingEnvironment = env;} public IHostingEnvironment HostingEnvironment {get;} public void ConfigureServices (IServiceCollection services) {if (HostingEnvironment.IsDevelopment ()) {/ / Development configuration} else {/ / Staging/Production configuration} var contentRootPath = HostingEnvironment.ContentRootPath;}}

The IHostingEnvironment service can also be injected directly into the Configure method to set up the processing pipeline:

/ / example 3:public void Configure (IApplicationBuilder app, IHostingEnvironment env) {if (env.IsDevelopment ()) {/ / In Development, use the DeveloperExceptionPage app.UseDeveloperExceptionPage ();} else {/ / In Staging/Production, route exceptions to / error app.UseExceptionHandler ("/ error");} var contentRootPath = env.ContentRootPath;}

You can inject IHostingEnvironment into the Invoke method when creating custom middleware (for those of you who want to learn about middleware, you can move on to Chapter 4):

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;} 7.IApplicationLifetime interface

Start and close activities after IApplicationLifetime allows. The three properties on the interface are the unmark used to register the Action method that defines the startup and shutdown events.

Unmark

Trigger condition

ApplicationStarted

The host is fully booted.

ApplicationStopped

The host is completing a normal shutdown. All requests should be processed. The shutdown is blocked until this event is completed.

ApplicationStopping

The host is performing a normal shutdown. Still processing the request. The shutdown is blocked until this event is completed.

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}}

StopApplication means to request the termination of the application. The following class closes the application normally using StopApplication when calling the class's Shutdown method:

Public class MyClass {private readonly IApplicationLifetime _ appLifetime; public MyClass (IApplicationLifetime appLifetime) {_ appLifetime = appLifetime;} public void Shutdown () {_ appLifetime.StopApplication ();} 8. Scope verification

If the application environment is Development, CreateDefaultBuilder sets ServiceProviderOptions.ValidateScopes to true. If ValidateScopes is set to true, the default service provider application performs a check to verify the following:

● scoped services cannot be resolved directly or indirectly from the root service provider.

●-scoped services are not directly or indirectly injected into the singleton (the lifecycle of the service).

To always verify the scope (including validation in the lifecycle environment), configure ServiceProviderOptions using UseDefaultServiceProvider on the host generator:

WebHost.CreateDefaultBuilder (args) .UseDefaultServiceProvider ((context, options) = > {options.ValidateScopes = true;}) so far, I believe you have a deeper understanding of "how ASP.NET Core configures and manages Web hosts". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report