.NET Core第5天_IWebHostEnvironment 的用途是捨麼?

IWebHostEnvironment用於在runtime期間判斷目前在捨麼環境執行


 預設產生的Startup.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MyCore0
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

    }
}

於Configure傳入的參數可以看到
IWebHostEnvironment的蹤影(.net core 第2版的IHostingEnviroment 為其前身)
3.1後IWebHostEnvironment則變去Implement  IHostingEnviroment 



主要能提供目前正在執行的Web hosting Environment資訊
使用時要引入Microsoft.AspNetCore.Hosting 這個Namespace



此介面的定義:

1
public interface IWebHostEnvironment : Microsoft.Extensions.Hosting.IHostEnvironment

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.iwebhostenvironment?view=aspnetcore-3.1


在ASP.NET Core3.1 Default將環境分為三種:
IsDevelopment:開發環境
Checks if the current hosting environment name is Development.
預設模式,為在開發應用時期用的環境

IsStaging:暫時測試(預演)環境
Checks if the current hosting environment name is Staging.
部屬到正式生產環境中最後測試的環境

IsProduction:正式環境
Checks if the current hosting environment name is Production.


額外的第四種則是確認某一指定值是否就是目前的執行環境名
True if the specified name is the same as the current environment, otherwise false.
Compares the current hosting environment name against the specified value.
會忽略大小寫!!

而要有這些環境擴充屬性需要有Microsoft.Extensions.Hosting此參考
上述這些Extension methods被定義於
Microsoft.AspNetCore.Hosting命名空間下的HostingEnvironmentExtensions Class








當中定義兩屬性




1.WebRootPath − Path of the www folder(Gets or sets the absolute path to the directory that contains the web-servable application content files)

2.ContentRootPath − Path of the root folder which contains all the Application files(Gets or sets an IFileProvider pointing at WebRootPath.)



實際輸出觀察

Test Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MyCore0
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("1st Middleware in. \r\n");
                await context.Response.WriteAsync(String.Format("Is Development Env:{0} \r\n", env.IsDevelopment()));
                await context.Response.WriteAsync(String.Format("Is Staging Env:{0} \r\n", env.IsStaging()));
                await context.Response.WriteAsync(String.Format("Is Production Env:{0} \r\n", env.IsProduction()));
                await context.Response.WriteAsync(String.Format("Environment Name:{0} \r\n", env.EnvironmentName));
                await context.Response.WriteAsync(String.Format("Is Match Current Environment Name:{0} \r\n", env.IsEnvironment("Development")));
                await context.Response.WriteAsync(String.Format("Is Match Current Environment Name:{0} \r\n", env.IsEnvironment("Staging")));
                await context.Response.WriteAsync(String.Format("WebRootPath:{0} \r\n", env.WebRootPath));
                await context.Response.WriteAsync(String.Format("ContentRootPath:{0} \r\n", env.ContentRootPath));
                await context.Response.WriteAsync(String.Format("ApplicationName:{0} \r\n", env.ApplicationName));
            });
        }

    }
}





在這我們會發現預設是Development
這是為何呢?
我們到專案屬性面板的偵錯看到



.Net Core於runtime期間會查一個環境變數
叫做ASPNETCORE_ENVIRONMENT,依此環境變數的值
來決定目前是不是Development或者Staging或者Production。



Ref:

[鐵人賽 Day16] ASP.NET Core 2 系列 - 多重環境組態管理 (Multiple Environments)

What is the role of IWebHostEnvironment interface in C# ASP.NET Core?


ASP.NET Core 2.2 -> 3.0 upgrade. env.IsDevelopment() not found

[.net core]如何在開發階段透過Visual Studio設定不同的執行環境 (環境變數)













留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題