.NET Core第5天_IWebHostEnvironment 的用途是舍麽?

IWebHostEnvironment用於在runtime期间判断目前在舍麽环境执行

预设产生的Startup.cs

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

此介面的定义:

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.

额外的第四种则是确认某一指定值是否就是目前的执行环境名
IsEnvironment :
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中

当中定义两属性
https://ithelp.ithome.com.tw/upload/images/20210905/20107452tkJ2u4tbaM.png

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

https://ithelp.ithome.com.tw/upload/images/20210905/20107452OxuvPF3js9.png

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

实际输出观察
Test Code:

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

    }
}

https://ithelp.ithome.com.tw/upload/images/20210905/20107452CEff4HyIBH.png

在这我们会发现预设是Development
这是为何呢?
我们到专案属性面板的侦错看到

https://ithelp.ithome.com.tw/upload/images/20210905/20107452boheeea36P.png

.Net Core於runtime期间会查一个环境变数
叫做ASPNETCORE_ENVIRONMENT,依此环境变数的值
来决定目前是不是Development或者Staging或者Production。

Ref:

[铁人赛 Day16] ASP.NET Core 2 系列 - 多重环境组态管理 (Multiple Environments)
https://blog.johnwu.cc/article/ironman-day16-asp-net-core-multiple-environments.html

What is the role of IWebHostEnvironment interface in C# ASP.NET Core?
https://www.tutorialspoint.com/what-is-the-role-of-iwebhostenvironment-interface-in-chash-asp-net-core

ASP.NET Core 2.2 -> 3.0 upgrade. env.IsDevelopment() not found
https://stackoverflow.com/questions/58070476/asp-net-core-2-2-3-0-upgrade-env-isdevelopment-not-found

[.net core]如何在开发阶段透过Visual Studio设定不同的执行环境 (环境变数)
https://blog.alantsai.net/posts/2019/01/faq-how-to-change-executing-environment-in-visual-studio#WizKMOutline_1547648931365459

本文同步发表至个人部落格
https://coolmandiary.blogspot.com/2020/11/net-coreiwebhostenvironment.html


<<:  Rails belong_to

>>:  .Net Core Web Api_笔记04_HTTP资源操作模式Put

Docker:Docker Hub Pull 流程

什麽是Docker Hub? 就如GitHub一样,只是Docker Hub是一个存放Docker ...

[第28天]理财达人Mx. Ada-SMA 指标

前言 本文说明使用TA-Lib函式库计算SMA指标。 SMA指标 简单移动平均线(SMA:simpl...

总结与心得

经过漫长的环境设定与软件安装後 终於把 SQL Server Failover Cluster 基本...

简报版-第七章-从AI人脸技术加持!看「有影片将不再有真相!?」

其实原本最初规画想要做Index方式的纪录,然後多增加一些没写到的面向 不过,总是计画赶不上变化 ...

【心得】你今天青蛙了吗?flex之路-flex设定了宽却没有用???

前言 曾经有一段瞎摸索的时间,老是不知道为什麽flex时灵时不灵 歪着脑袋想不通为什麽... 直到摸...