• 【.Net Core】程序相关各种全局文件


    Program.cs

    ASP.NET Core Web应用被创建后,项目中会产生两个文件:Program.cs、Startup.cs,程序中把Program.cs作为Web应用程序的入口,程序启动时会调用Startup.cs类。

    这是我们配置Web Host的应用程序的入口。 program类配置应用程序基础结构,如Web Host,日志记录,依赖注入容器,IIS集成等。它们是由program类中Main方法的createdefaultbuilder方法创建,配置和构建的。

    ASP.NET MVC、WebApi中 Global.asax、FilterConfig.cs 和 RouteConfig.cs等类都被Program.cs、Startup.cs取而代之。

    什么是Program.cs?

    Program类包含的Main方法是ASP.NET Core应用的入口点。Main方法类似于控制台应用程序 的Main方法。这是因为所有.NET Core应用程序基本上都是控制台应用程序。我们通过控制台应用程序构建其他类型的应用程序,例如MVC Web应用程序或Razor page 应用程序。

    Program类的主要目的是配置应用程序基础结构。

    Program类在启动时创建Web Host。然后,它配置日志记录、依赖注入容器、Kestrel Web服务器、IIS集成等。它还将框架服务添加到DI容器中,以便我们可以使用它。 Program类的代码是vs自动生成的,并且对于大多数项目来说很可能已经足够了。

    什么是web host?

    Web host负责启动应用程序并运行它。 在应用程序启动时创建。 Web host创建一个服务器,该服务器侦听HTTP请求。 它配置请求管道(或中间件管道)。 另外,它设置了DI容器,我们在其中添加了服务。 管理服务的生命周期也是Web host的任务。

    main方法

    打开program.cs。这个类只有一个Main方法

    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Hosting;
    namespace HelloWorld
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    这是我们应用程序的入口。

    下图显示了如何创建web host

    CreateWebHostBuilder 创建主机并为其提供配置。build方法使用提供的配置进行构建。Run方法运行它,然后侦听HTTP请求
    在这里插入图片描述
    ASP.NET Core中Program.cs类的Main方法

    创建主机

    CreateWebHostBuilder是static方法,它可以创建和配置主机,然后返回。

    public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    上面的语法称为“ expression bodied function member(表达式方法体)”。是C#6中引入的功能 。上面的代码与以下代码等效。

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
            {
                return WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    上面的方法使用Web Host helper静态类。WebHost helper类的CreateDefaultBuilder方法负责使用所需配置创建IWebHostBuilder实例。

    CreateDefaultBuilder

    • 在CreateDefaultBuilder中执行以下操作。
    • 将ContentRoot设置为Directory.GetCurrentDirectory。
    • 加载可选配置启用记录
      • Appsettings.json
      • Appsettings.{Environment}.json。
      • User secrets。
      • 环境变量
      • 命令行参数。
    • 启用记录
    • 设置依赖项注入容器。
    • 将Kestre l 配置为Web服务器
    • 将框架服务添加到DI容器
    • 将Kestrel与IIS集成

    我们可以从ASP.NET Core元数据包中查看CreateDefaultBuilder的源代码。

    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;
    }
    
    • 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
    • 41
    • 42
    • 43
    • 44

    让我们来一行一行的看看

    设置ContentRoot

    builder.UseContentRoot(Directory.GetCurrentDirectory());
    
    • 1

    这将ContentRoot设置为 Directory.GetCurrentDirectory。这基本上将当前目录设置为应用程序的根目录。

    加载配置文件:从各种来源按以下顺序加载配置

    1. Appsettings.json。
    2. appsettings.{Environment} .json。
    3. User secrets。
    4. 环境变量。
    5. 命令行参数。
    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);
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    启用记录

    接下来是启用和配置日志记录的代码。

    ConfigureLogging((hostingContext, logging) =>
    {
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();
    }).
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    这将读取配置文件的“Logging”部分中指定的配置规则,并配置控制台和调试输出的日志记录。

    设置DI容器

    UseDefaultServiceProvider方法设置并注入依赖项容器。

    UseDefaultServiceProvider((context, options) =>
    {
      options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
    });
    
    • 1
    • 2
    • 3
    • 4

    配置WebHost

    最后,代码调用ConfigureWebDefaults方法。此方法配置Web Host。

    internal static void ConfigureWebDefaults(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration((ctx, cb) =>
        {
            if (ctx.HostingEnvironment.IsDevelopment())
            {          StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
            }
        });
        builder.UseKestrel((builderContext, options) =>
        {     options.Configure(builderContext.Configuration.GetSection("Kestrel"));
        })
        .ConfigureServices((hostingContext, services) =>
        {
            services.PostConfigure<HostFilteringOptions>(options =>
            {
                if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
                {
                   var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                   options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
    
                }
            });
                        new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));
            services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();
            if (string.Equals("true", hostingContext.Configuration["ForwardedHeaders_Enabled"], StringComparison.OrdinalIgnoreCase))
            {
                services.Configure<ForwardedHeadersOptions>(options =>
                {
                    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                            options.KnownNetworks.Clear();
                    options.KnownProxies.Clear();
                });
                services.AddTransient<IStartupFilter, ForwardedHeadersStartupFilter>();
            }
            services.AddRouting();
        })
        .UseIIS()
        .UseIISIntegration();
    }
    
    • 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

    Kestrel

    第一种方法告诉主机使用Kestrel Web服务器。Kestrel是基于跨平台托管HTTP服务器的。该服务器允许ASP.NET Core应用程序在Windows以外的操作系统上运行。

    builder.UseKestrel((builderContext, options) =>
    {
    options.Configure(builderContext.Configuration.GetSection("Kestrel"));
    })
    
    • 1
    • 2
    • 3
    • 4

    配置服务

    配置服务并将其添加到DI 容器。

    ConfigureServices((hostingContext, services) =>
    {
       //服务
    }
    
    • 1
    • 2
    • 3
    • 4

    使用IIS或集成

    配置IIS服务器以托管应用程序。我们可以通过两种方式托管应用程序。一个在进程中托管,另一个在进程外托管。in Process在IIS Process内部运行该应用程序,并由配置UseIIS()。Out of process在单独的进程中运行,并使用Kestrel服务器。然后,IIS充当反向代理,将请求转发到Kestrel。这是通过方法配置的UseIISIntegration()。

    .UseIIS()
    .UseIISIntegration();
    
    • 1
    • 2

    Startup class

    主机已创建和配置,但是在构建和运行之前,我们需要使用应用程序进行进一步配置。我们在Startup类中执行此操作。默认情况下,该类被命名为Startup类。通过使用UseStartup方法,我们使构建者知道启动类的位置。

    .UseStartup<Startup>()
    
    • 1

    启动类包含两个方法。一个是ConfigureServices(是可选的),另一个是Configure。在ConfigureServices方法中,我们配置在应用程序中创建的服务并将其添加到DI容器中。在Configure方法中,我们通过添加中间件的方式来创建请求管道。

    CreateWebHostBuilder将从启动类调用ConfigureServices和configure方法,并进一步配置主机

    编译并运行

    CreateWebHostBuilder创建Web Host并将其返回。通过Build与Run方法调用,并且启动应用程序从而开始监听HTTP请求。

    CreateWebHostBuilder(args).Build().Run();
    
    • 1

    Startup.cs

    Startup.cs的作用是:在项目中用到的静态文件、管道、服务、日志、路由、数据库连接、过滤器的注册等所有有关程序运行时使用。

    项目Startup.cs类:

    public class Startup
        {
            public IConfiguration Configuration { get; }
    
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<AppDbContext>(options => 
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                );
    
                services.AddMvc();
                //自动添加服务依赖
                //AddTransient 每次注册服务,会创建新的仓库,以保证仓库之间独立 
                //仓库依赖注入系统
                services.AddTransient<INoodleRepository, NoodleRepository>(); 
                services.AddTransient<IFeedbackRepository,FeedbackRepository>();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                //app.UseMvcWithDefaultRoute();  默认路由
    
                app.UseStaticFiles();
    
                app.UseAuthentication();
    
                app.UseMvc(route => 
                {
                    route.MapRoute("default","{controller=Home}/{action=Index}/{id?}");
                });
    
                app.Run(async (context) =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            }
        }
    
    • 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
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    从上面可以看出Startup.cs主要包含两个方法:ConfigureServices、Configure

    1.ConfigureServices方法:将服务注册到容器。eg:第三方组件

    services.AddMvc(); //注入MVC模块,包含MvcCore和常用的第三方库的服务和方法

    services.AddTransient<INoodleRepository, NoodleRepository>(); //自动添加服务依赖。瞬时注入,每次都会创建一个新的对象,以保证对象之间的独立性

    services.AddSingleton<IStudentRepository,MockStudentRepository>(); //单例注入,创建的对象在所有的地方所有的请求会话创建的都是相同的

    services.AddScoped<IStudentRepository,MockStudentRepository>(); //作用域注入,创建的对象在同一个请求会话时是相同的

    2.Configure方法:配置Http请求管道。 eg:session、cookie

    HostingEnvironment.IsDevelopment(); //判断当前运行环境是否是 Microsoft,如果是则返回true。

    //如果要判断其他运行环境,比如 Linux,则使用 env.IsEnvironment(“environmentname”) environmentname为要验证的环境名称。

    app.UseStaticFiles(); //使用静态文件

    //使用MVC管道路径,可以在这个配置路由等操作

    app.UseMvc(route =>
    {
    route.MapRoute(“default”,“{controller=Home}/{action=Index}/{id?}”);
    });

    实战

    1. .net core使用session:

    ConfigureServices方法: services.AddSession();    //注入session
    
    Configure方法:app.UseSession();
    
    Controller:  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    //[Route("[controller]/[action]")]
        public class HomeController : Controller
        {
            // GET: /<controller>/
            public IActionResult Index()
            {
                HttpContext.Session.SetString("code","123456");
    
                return View();
            }
    
            public String About()
            {
                ViewBag.Code = HttpContext.Session.GetSession("code");
                return View();
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2. .net core使用Cache:

     ConfigureServices方法: services.AddMemoryCache();   //注册缓存服务
    
     Controller:
    
    • 1
    • 2
    • 3
    public class HomeController : Controller
        {
            private IMemoryCache _cache;
          
            public HomeController (IMemoryCache memoryCache )
            {
                  _cache = memoryCache ;
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    设置缓存: _cache.set(“key”,“value”);

    移除缓存: _cache.remove(“key”);

    appsettings.json:Development(开发)Staging(预演)Production(生产)

    ASP.NET Core基于以下环境变量读取配置文件 appsettings.json:Development(开发)Staging(预演)Production(生产)它们的文件名都是诸如这样的名称 appsettings.Development.json。
    在运行的时候我们怎么知道是从哪个文件取值呢?
    首先这个值来自键值对的配置,总结一下设置变量的方式,一共有两个:

    1. 通过使用关键字来设置 DOTNET_ENVIRONMENT。
    2. 通过键值ASPNETCORE_ENVIRONMENT来设置。
    3. 其中ASPNETCORE_ENVIRONMENT优先级高于 DOTNET_ENVIRONMENT。

    再总结一下设置运行时环境的方法。

    (1)如果你是代码开发者,使用Visual Studio开发者,在工具里运行和调试软件,右键选择项目属性,如图:
    在这里插入图片描述
    其实配置文件保存在:Properties \ launchSettings.json

    "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          },
          "nativeDebugging": true
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (2)如果你使用的Visual Studio Code,那么你可直接编辑或新建文件.vscode / launch.json
    例如:

    {
        "version": "0.2.0",
        "configurations": [
            {
                "name": ".NET Core Launch (web)",
                "type": "coreclr",
                // Configuration ommitted for brevity.
                "env": {
                    "ASPNETCORE_ENVIRONMENT": "Development",
                    "ASPNETCORE_URLS": "https://localhost:5001",
                    "ASPNETCORE_DETAILEDERRORS": "1",
                    "ASPNETCORE_SHUTDOWNTIMEOUTSECONDS": "3"
                }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    (3)如果你只是运行代码那么在服务器上需要设置环境变量,一种是临时设置,一种是全局设置,各命令行需要根据操作系统变化而不同,(自行百度Linux各系统设置环境变量的方法)例如Windows下:

    set ASPNETCORE_ENVIRONMENT=Staging
    dotnet run --no-launch-profile
    
    • 1
    • 2

    (4)如果你什么都不做,那默认加载的是Production,也就是appsettings.Production.json(不建议这么做)。

    (5)如果你是托管在IIS宿主下,那么是还会有一个Web.config的供IIS加载,可在Web.config中添加环境变量例如:

    <environmentVariables>
              <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
              <environmentVariable name="COMPLUS_ForceENC" value="1" />
            </environmentVariables>
    
    • 1
    • 2
    • 3
    • 4

    (6)如果你是在Linux下部署依靠supervisor托管程序,那么在supervisor配置文件中就有相关环境变量的配置:

    [program:Own.WebSite]
    command=/bin/bash -c "dotnet Own.WebSite.dll"
    directory=/home/wwwroot/Own.WebSite/
    stderr_logfile=/tmp/Own.WebSite.error.log
    stdout_logfile=/tmp/Own.WebSite.stdout.log
    environment=ASPNETCORE_ENVIRONMENT=Production
    user=root
    stopsignal=INT
    autostart=true
    autorestart=true
    startsecs=3
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    launchsettings.json

    • 您将在项目根文件夹的**“Properties”**文件夹中找到此文件。
    • 当我们从 Visual Studio 或使用.NET Core CLI 运行此 ASP.NET Core 项目时,将使用此文件中的设置。
    • 此文件仅用于本地开发环境。我们不需要把它发布到生产环境的 Asp.net Core 程序中。
    • 如果您希望您的 Asp.Net Core 应用程序在发布和部署应用程序时使用某些独立的设置,请将它们存储在
      appsettings.json 文件中。我们通常将应用程序的配置信息存储在此文件中,比如数据库连接字符串。
    • 我们还可以使用不同环境的 appsettings.json 文件。例如,appsettings.Staging.json
      用于临时环境。在- ASP.NET Core 中,除了 appsettings.json
      文件外,我们还可以配置源,如环境变量,用户密钥,命令行参数甚至创建属于我们自己的自定义配置源。

    launchSettings.json 文件:

    {
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:3290",
          "sslPort": 0
        }
      },
      "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "StudentManagement": {
          "commandName": "Project",
          "launchBrowser": true,
          "applicationUrl": "http://localhost:5000",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }
      }
    }
    
    
    • 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

    请注意,我们有两个配置信息:

    IIS Express 和 StudentManagement

    当我们通过按CTRL + F5或只是F5从 Visual Studio 运行项目时。 默认情况下,使用调用配置文件名称"commandName": “IISExpress”,。 另外一种情况,如果我们使用.NET Core CLI(dotnet run)运行项目,则使用带有"commandName": “Project”,的配置文件 。
    在这里插入图片描述
    我们可以通过单击 Visual Studio 中的下拉列表来更改要使用的配置文件中 .commandName 属性,修改默认设置。
    默认值可以是:

    • 项目
    • IISExpress
    • IIS

    此值与项目文件中的AspNetCoreHostingModel元素的值会有对应关系,会一起指定要启动的内部和外部 Web 服务器(反向代理服务器)。

    commandNameAspNetCoreHostingModel 的值Internal Web Server(内部服务器)External Web Server(外部服务器)
    项目忽略托管设置的值只使用一个 Web 服务器 - Kestrel只使用一个 Web 服务器 - Kestrel
    IISExpress进程内托管(InProcess)只使用一个 Web 服务器 - IIS Express只使用一个 Web 服务器 - IIS Express
    IISExpress进程外托管(OutOfProcess)KestrelIIS Express
    IIS进程内托管(InProcess)只使用一个 Web 服务器 - IIS只使用一个 Web 服务器 - IIS
    IIS进程外托管(OutOfProcess)KestrelIIS

    您还可以通过直接编辑 launchSettings.json 文件中的设置,也可以使用 Visual Studio 提供的图形用户界面(GUI)更改设置。

    通过 GUI 来设置

    在 Visual Studio 的解决方案资源管理器中右键单击项目名称,然后从上下文菜单中选择“属性”。 单击项目“属性”窗口中的“调试”选项卡,如下图:
    在这里插入图片描述
    使用 GUI 我们可以更改launchSettings.json文件中的设置。

    注意,环境变量“ASPNETCORE_ENVIRONMENT”设置的默认设置为“Development”。

    我们可以将此值更改为Staging或Production,具体取决于我们是在Staging还是Production环境中运行此项目。

    我们还可以添加新的环境变量。这些环境变量在我们的 Asp.Net Core 应用程序中都可用,我们可以包含根据这些环境变量的值有条件地执行的代码。

    例如,请参考Startup.cs文件中的Configure()方法中的以下代码

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
              //其他的代码
    
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    仅当环境为“ Development”时,才会显示“ 开发异常页面”。

    来源

    ASP.NET Core中Startup.cs介绍
    ASP.NET Core Program.cs
    ASP.NET Core 中appsettings各环境设置以及使用
    ASP.NET Core 中 launchsettings.json 启动配置文件

  • 相关阅读:
    unix多进程多线程
    vue3中toRef和toRefs的用法
    红黑树的插入底层【C++】
    2.29log | 968.监控二叉树,509. 斐波那契数,70. 爬楼梯,746. 使用最小花费爬楼梯
    Makefile文件详解
    基于Java+JSP+MySQL基于SSM的物流公司物流订单管理系统-计算机毕业设计
    代码(Python、Java)实现分组求和
    iphone如何使用itunes恢复数据?
    学习如何使用最强大的 JavaScript 函数
    多分类问题的precision和recall以及F1 scores的计算
  • 原文地址:https://blog.csdn.net/weixin_44231544/article/details/125558487