In ASP. NET Core applications, how does one set and obtain information related to the execution environment ?, Asp. netcore

Source: Internet
Author: User
Tags webhost

In ASP. NET Core applications, how does one set and obtain information related to the execution environment ?, Asp. netcore

HostingEnvironment is a description of the current execution environment of the application. It is a collective term for all types and corresponding objects that implement the IHostingEnvironment interface. As shown in the following code snippet, the description of the execution environment carried by a HostingEnvironment object is reflected in the six attributes that define this interface. ApplicationName and EnvironmentName represent the name of the current application and the name of the execution environment respectively. WebRootPath and ContentRootPath are the paths pointing to two root directories. The former is used to store resources that can be accessed by the outside world through HTTP requests, the directory to which the latter points is the internal resources of the application. For the ContentRootFileProvider and WebRootFileProvider attributes of this interface, the returned results are the FileProvider objects for these two directories. The HostingEnvironment type shown below is the default implementation of the IHostingEnvironment interface. [This Article has been synchronized to ASP. NET Core framework secrets]

   1: public interface IHostingEnvironment
   2: {
   3:     string         ApplicationName { get; set; }
   4:     string         EnvironmentName { get; set; }
   5:     IFileProvider  ContentRootFileProvider { get; set; }
   6:     string         ContentRootPath { get; set; }
   7:     IFileProvider  WebRootFileProvider { get; set; }
   8:     string         WebRootPath { get; set; }
   9: }
  10:  
  11: public class HostingEnvironment : IHostingEnvironment
  12: {
  13:     string         ApplicationName { get; set; }
  14:     string         EnvironmentName { get; set; }
  15:     IFileProvider  ContentRootFileProvider { get; set; }
  16:     string         ContentRootPath { get; set; }
  17:     IFileProvider  WebRootFileProvider { get; set; }
  18:     string         WebRootPath { get; set; }
  19: }
1. ApplicationEnvironment

Next, we will introduce in detail the source of the description of the execution environment carried by the HostingEnvironment object. However, before that, we need to understand another type named ApplicationEnvironment, which is defined in "Microsoft. extensions. platform1_actions "in the NuGet package. We can also see from its name that this object also describes information related to the execution environment, and the information it carries is carried by the following four attribute members, they indicate the application name, base path, version, and used.. NET Framework.

   1: public class ApplicationEnvironment
   2: {
   3:     public string         ApplicationName {  get; }
   4:     public string         ApplicationBasePath {  get; }
   5:     public string         ApplicationVersion {  get; }
   6:     public FrameworkName  RuntimeFramework { get; }
   7: }

To obtain an ApplicationEnvironment object to describe the current execution environment, we need to use the following object called PlatformServices. Its Application attribute returns the ApplicationEnvironment object we need. Because this type does not have a public constructor, we cannot directly instantiate a PlatformServices object, but we can use the Default property to obtain this singleton object.

   1: public class PlatformServices
   2: {
   3:     private PlatformServices();
   4:     public ApplicationEnvironment     Application { get; }
   5:     public static PlatformServices    Default { get; }
   6: }

For an ApplicationEnvironment object, its ApplicationName, ApplicationVersion, and RuntimeFramework attributes determine the Assembly that defines the Main method of the program entry. Specifically, ApplicationName and ApplicationVersion return the Assembly name and version respectively, this compilation of this Assembly uses. the version of NET Framework corresponds to the RuntimeFramework attribute. As for the ApplicationBasePath attribute, it returns the path corresponding to the BaseDirectoryPath attribute of AppContext. This basic path is used during runtime to parse the actual path of the loaded target assembly. The values of these four attributes can be verified through the following program.

   1: public class Program
   2: {
   3:     public static void Main()
   4:     {
   5:         Assembly assembly = typeof(Program).GetTypeInfo().Assembly;
   6:         AssemblyName assemblyName = assembly.GetName();
   7:         ApplicationEnvironment env = PlatformServices.Default.Application;
   8:  
   9:         Debug.Assert(env.ApplicationBasePath == AppContext.BaseDirectory);
  10:         Debug.Assert(env.ApplicationName == assemblyName.Name);
  11:         Debug.Assert(env.ApplicationVersion == assemblyName.Version.ToString());
  12:         Debug.Assert(env.RuntimeFramework.ToString() == assembly.GetCustomAttribute<TargetFrameworkAttribute>().FrameworkName);
  13:     }
  14: }

If we do not explicitly set the application name, the application name in the ApplicationName attribute of the current HostingEnvironment comes from the same name attribute of the ApplicationEnvironment object. The four attributes of HostingEnvironment include ApplicationName (excluding the WebRootFileProvider and ContentRootFileProvider attributes, because they are determined by the corresponding ContentRootPath and WebRootPath attributes) can be set through WebHostOptions. Through the introduction in the previous chapter, we know that the WebHostOptions object is created based on the configuration adopted by WebHostBuilder. Therefore, we can use the configuration method to determine the execution environment.

Ii. Configuration and WebHostOptions

For settings that are carried by four attributes of HostingEnvironment (ApplicationName, EnvironmentName, WebRootPath, and ContentRootPath) related to the execution environment, the WebHostOptions object has the corresponding attributes, the latter is the data source of the former. Because the WebHostOptions object is created by WebHostBuilder Based on the configuration it uses, these settings are initially derived from the configuration used. It is worth mentioning that if the EnvironmentName attribute is not explicitly set, it uses the default value "Production ".

Because WebHostBuilder uses environment variables as the configuration source and uses "ASPNETCORE _" as the prefix used for environment variable filtering, therefore, we can initialize the execution environment options carried by HostingEnvironment by setting environment variables as follows.

   1: Environment.SetEnvironmentVariable("ASPNETCORE_APPLICATIONNAME", "MyApp");
   2: Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Staging");
   3: Environment.SetEnvironmentVariable("ASPNETCORE_WEBROOT", @"c:\myapp\wwwroot\");
   4: Environment.SetEnvironmentVariable("ASPNETCORE_CONTENTROOT", @"c:\myapp\contentroot");
   5:  
   6: new WebHostBuilder()
   7:     .UseConfiguration(new ConfigurationBuilder().AddJsonFile("weboptions.json"))
   8:     .ConfigureServices(svcs => {
   9:         IHostingEnvironment env = svcs.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
  10:         Debug.Assert(env.ApplicationName == "MyApp");
  11:         Debug.Assert(env.EnvironmentName == "Staging");
  12:         Debug.Assert(env.WebRootPath == @"c:\myapp\wwwroot\");
  13:         Debug.Assert(env.ContentRootPath == @"c:\myapp\contentroot");
  14:     })
  15:     .UseKestrel()
  16:     .Build();

Although WebHostBuilder uses environment variables as the Configuration source by default, we can create a Configuration object explicitly and call its extension method UseConfiguration for "import ". For the above program, if we define the configuration in a JSON file (weboptions. json), you only need to call the UseConfiguration method to import the corresponding configuration as follows before creating a WebHost.

Weboptions. json:

   1: {
   2:   "applicationName": "MyApp",
   3:   "environment"    : "Staging",
   4:   "webRoot"        : "c:\\myapp\\wwwroot",
   5:   "contentRoot"    : "c:\\myapp\\contentroot"
   6: }

Program

   1: new WebHostBuilder()
   2:     .UseConfiguration(new ConfigurationBuilder().AddJsonFile("weboptions.json").Build())
   3:     .ConfigureServices(svcs => {
   4:         IHostingEnvironment env = svcs.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
   5:         Debug.Assert(env.ApplicationName  == "MyApp");
   6:         Debug.Assert(env.EnvironmentName  == "Staging");
   7:         Debug.Assert(env.WebRootPath       == @"c:\myapp\wwwroot\");
   8:         Debug.Assert(env.ContentRootPath  == @"c:\myapp\contentroot");
   9:     })
  10:     .UseKestrel()
  11:     .Build();
Iii. Special ApplicationName

For the four attributes of HostingEnvironment, The ApplicationName of the Application name is special. Although its initial value comes from configuration, this attribute will be overwritten when we call the Configure method or UseStartup method. The following program differs from the above in that the Configure method is called before the WebHost is created. The application name ("MyApp") set using the environment variable will become invalid.

   1: Environment.SetEnvironmentVariable("ASPNETCORE_APPLICATIONNAME", "MyApp");
   2: new WebHostBuilder()
   3:     .ConfigureServices(svcs => {
   4:         IHostingEnvironment env = svcs.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
   5:         Debug.Assert(env.ApplicationName != "MyApp");
   6:     })
   7:     .UseKestrel()
   8:     .Configure(app => {})
   9: .Build();

In fact, the answer to this question is provided in "application entry -- Startup. The following shows the definitions of Configure and UseStartup extension methods used by WebHostBuilder to register Startup. We can clearly see that they all set the name of the current application before creating and registering Startup.

   1: public static class WebHostBuilderExtensions
   2: {    
   3:     public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action<IApplicationBuilder> configureApp)
   4:     {
   5:         var startupAssemblyName = configureApp.GetMethodInfo().DeclaringType.GetTypeInfo().Assembly.GetName().Name;
   6:  
   7:         return hostBuilder
   8:             .UseSetting("applicationName", startupAssemblyName)
   9:             …
  10:     }
  11:  
  12:     public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, Type startupType)
  13:     {
  14:         var startupAssemblyName = startupType.GetTypeInfo().Assembly.GetName().Name;
  15:         return hostBuilder
  16:             .UseSetting("ApplicationName", startupAssemblyName)
  17:             ...           
  18:     }
  19: }

If we call the UseStartup method of WebHostBuilder to set a startup class, the Assembly name of this type will be used as the name of the current application. If we use the Configure method and provide an Action <IApplicationBuilder> type delegate object, the corresponding method of this delegate object is defined in which type, the program base name of this type will be used as the application name. In the latter case, the <IApplicationBuilder> object of the Action can be provided in the following two methods, which will eventually lead to a completely different application name.

   1: public static class Startup
   2: {
   3:     public static void Configure(IApplicationBuilder app);
   4: }
   5:  
   6: //Configure(app=>Startup.Configure(app))
   7: new WebHostBuilder()
   8:     .ConfigureServices(svcs => {
   9:         IHostingEnvironment env = svcs.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
  10:         Debug.Assert(env.ApplicationName == Assembly.GetEntryAssembly().GetName().Name);
  11:     })
  12:     .UseKestrel()
  13:     .Configure(app=>Startup.Configure(app))
  14:     .Build();
  15:  
  16: //Configure(Startup.Configure)
  17: new WebHostBuilder()
  18:     .ConfigureServices(svcs => {
  19:         IHostingEnvironment env = svcs.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
  20:         Debug.Assert(env.ApplicationName == typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
  21:     })
  22:     .UseKestrel()
  23:     .Configure(Startup.Configure)
  24:     .Build();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.