ASP.Net Core 5.0 MVC 配置文件读取,Startup 类中ConfigureServices 方法、Configure 方法的使用

配置文件读取

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 IActionResult Index()
        {

            ViewBag.Title = Configuration["Position:Title"];
            ViewBag.MyKey = Configuration["MyKey"];
            ViewBag.sName1 = Configuration["StudentList:0:sName"];
            ViewBag.sName2 = Configuration["StudentList:1:sName"];
            ViewBag.Default = Configuration["Logging:LogLevel:Default"];
            return View();
        }

新增index视图,复制以下内容

@*
    For more information on enabling MVC for empty projects, visit //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 应用使用 Startup 类,按照约定命名为 Startup。 Startup 类:

在应用启动时,ASP.NET Core 运行时会调用 ConfigureServices 和 Configure

ConfigureServices 方法

ConfigureServices 方法:

  • 可选。
  • 在 Configure 方法配置应用服务之前,由主机调用。
  • 其中按常规设置配置选项

主机可能会在调用 Startup 方法之前配置某些服务。 有关详细信息,请参阅主机

对于需要大量设置的功能,IServiceCollection 上有 Add{Service} 扩展方法。 例如,AddDbContext、AddDefaultIdentity、AddEntityFrameworkStores 和 AddRazorPages :

    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 方法中可用。 服务通过依赖关系注入或 ApplicationServices 进行解析。

Configure 方法

Configure 方法用于指定应用响应 HTTP 请求的方式。 可通过将中间件组件添加到 IApplicationBuilder 实例来配置请求管道。 Configure 方法可使用 IApplicationBuilder,但未在服务容器中注册。 托管创建 IApplicationBuilder 并将其直接传递到 Configure

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

每个 Use 扩展方法将一个或多个中间件组件添加到请求管道。 例如,UseStaticFiles 配置中间件提供静态文件

请求管道中的每个中间件组件负责调用管道中的下一个组件,或在适当情况下使链发生短路。

可以在 Configure 方法签名中指定其他服务,如 IWebHostEnvironmentILoggerFactory 或 ConfigureServices 中定义的任何内容。 如果这些服务可用,则会被注入。