当前位置 博文首页 > 明志德道:ASP.Net Core 5.0 MVC AppSettings配置文件读取,Sta

    明志德道:ASP.Net Core 5.0 MVC AppSettings配置文件读取,Sta

    作者:明志德道 时间:2021-02-05 14:24

    配置文件读取

    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 应用使用 Startup 类,按照约定命名为 Startup。 Startup 类:

    • 可选择性地包括 ConfigureServices 方法以配置应用的服务。 服务是一个提供应用功能的可重用组件。 在 ConfigureServices 中注册服务,并通过依赖关系注入 (DI) 或 ApplicationServices 在整个应用中使用服务。
    • 包括 Configure 方法以创建应用的请求处理管道。

    在应用启动时,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 模板配置的管道支持:

    • 开发人员异常页
    • 异常处理程序
    • HTTP 严格传输安全性 (HSTS)
    • HTTPS 重定向
    • 静态文件
    • ASP.NET Core MVC 和 Razor Pages
       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 中定义的任何内容。 如果这些服务可用,则会被注入。

    bk