Read Configurations in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

Select Project and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select App Settings File item and click Add button to Finish

In appsettings.json file and new configurations as below:

{
  "Message": "Hello World",
  "MyConfigs": {
    "Config1": "Value of Config 1",
    "Config2": "Value of Config 2",
    "Config3": "Value of Config 3"
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}




Create new folder named Pages. In this folder, create new Razor Page named Index as below:

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public string Result1 { get; set; }
        public string Result2 { get; set; }
        public string Result3 { get; set; }
        public string Result4 { get; set; }
        public string Result5 { get; set; }

        private IConfiguration configuration;

        public IndexModel(IConfiguration _configuration)
        {
            configuration = _configuration;
        }

        public void OnGet()
        {
            Result1 = configuration["Message"];
            Result2 = configuration["MyConfigs:Config1"];
            Result3 = configuration["MyConfigs:Config2"];
            Result4 = configuration["MyConfigs:Config3"];
            Result5 = configuration["Logging:Debug:LogLevel:Default"];
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    Result 1: @Model.Result1
    <br />
    Result 2: @Model.Result2
    <br />
    Result 3: @Model.Result3
    <br />
    Result 4: @Model.Result4
    <br />
    Result 5: @Model.Result5

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115

Output