在本章中,无涯教程将讨论与ASP.NET Core项目相关的配置,在Solution Explorer中,您将看到Startup.cs文件。如果您使用过ASP.NET Core的早期版本,则可能希望看到一个global.asax文件,该文件是您可以在Web应用程序启动期间编写要执行的代码的地方。
您还希望看到一个web.config文件,其中包含应用程序执行所需的所有配置参数。
在ASP.NET Core中,这些文件都消失了,而是从Startup.cs加载配置和启动代码。
文件中有一个Startup类,在该类中,您可以配置应用程序,甚至可以配置配置源。
链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_core/asp.net-core-configuration.html
来源:LearnFk无涯教程网
这是 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.Logging; namespace FirstAppDemo { public class Startup { //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 http://go.microsoft.com/fwlink/?LinkID=398940 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, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
在Startup类中,有两种方法将完成大部分工作。
在Solution Explorer 中,右键单击您的项目节点,然后选择 Add→New Item。
在左窗格中,选择 Installed→Code ,然后在中间窗格中,选择JSON File,将此文件命名为 AppSettings.json ,然后单击 Add 按钮,如上面的屏幕截图所示。
也可以让程序从文件中读取文本,而不是使用Hello World!Startup.cs中的字符串,在 AppSettings.json文件中添加以下代码。
{ "message": "Hello, World! this message is from configuration file..." }
现在,需要从Startup.cs文件访问此消息。这是 Startup.cs 文件的实现,该文件将从JSON文件读取以上消息。
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo { public class Startup { public Startup() { var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json"); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; } //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 http://go.microsoft.com/fwlink/?LinkID=398940 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) { app.UseIISPlatformHandler(); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } //Entry point for the application. public static void Main(string[] args) =7gt; WebApplication.Run<Startup>(args); } }
现在让无涯教程运行该应用程序。一旦运行该应用程序,它将产生以下输出。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)