配置文件读取1. 新建FirstController控制器 在appsettings文件内容替换成以下代码 { "Position": { "Title": "EditTool For human", "Name": "Joe Smith" },//json对象 "MyKey": "My appsettings.json Value", "StudentList": [ {"sName": "Jack"}, {"sName":"John"} ],//json数组 "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }//json对象嵌套 }, "AllowedHosts": "*" } 配置文件读取在Fristcontroller添加Index方法,复制以下内容 public IConfiguration Configuration { get; } //构造函数注入 configuration public FirstController(IConfiguration configuration) { Configuration = configuration; } public IActionResult Index() { //配置文件的读取 ViewBag.Title = Configuration["Position:Title"];//json对象 ViewBag.MyKey = Configuration["MyKey"]; ViewBag.sName1 = Configuration["StudentList:0:sName"];//json数组 ViewBag.sName2 = Configuration["StudentList:1:sName"]; ViewBag.Default = Configuration["Logging:LogLevel:Default"];//json嵌套对象 return View(); } 新增index视图,复制以下内容 @* For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 *@ @{ } <p> ViewBag.Title 的值: @ViewBag.Title</p> <p> ViewBag.MyKey的值: @ViewBag.MyKey</p> <p> ViewBag.sName1的值: @ViewBag.sName1</p> <p> ViewBag.sName2的值: @ViewBag.sName2</p> <p> ViewBag.Default的值: @ViewBag.Default</p> 运行测试效果
Startup 类ASP.NET Core 应用使用
在应用启动时,ASP.NET Core 运行时会调用 ConfigureServices 方法
主机可能会在调用 对于需要大量设置的功能,IServiceCollection 上有 public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>( options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddRazorPages(); } 将服务添加到服务容器,使其在应用和 Configure 方法Configure 方法用于指定应用响应 HTTP 请求的方式。 可通过将中间件组件添加到 IApplicationBuilder 实例来配置请求管道。 ASP.NET Core 模板配置的管道支持:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } 每个 请求管道中的每个中间件组件负责调用管道中的下一个组件,或在适当情况下使链发生短路。 可以在 |