Search code examples
c#asp.netrazorconfigurationrazor-pages

How do you read from appsettings.json in the same style as it's predecessor, webforms?


In WebForms we would have a web.config file that we could do ConfigurationManager.AppSettings["SomeKey"]; to retrieve the value from the key-value pair.

I've just started a project in .NET 5.0 and there doesn't seem a simple way to do something that seems to trivial?

I've looked online and have been unsuccessful in following tutorials on how to access these keys in appsettings.json from a .cshtml file using @ notation.

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "MyKey": "wwwwwwwwwww"
}

Index.cshtml:

<h1>
    Title - @ConfigurationManager.AppSettings["MyKey"];
</h1>

The above illustrates what I am trying to achieve, is there a simple way to do this rather than creating classes etc as I don't seem to be able to follow their examples.


Solution

  • To access configuration settings in a view in a .NET project, you should be able to use @ annotation. This is done by injecting the configuration into the page:

    @page
    @model Test5Model
    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration
    
    Configuration value for 'MyKey': @Configuration["MyKey"]
    

    Take this appsettings.json for example:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
      "Test": "Hello World",
      "ConnectionStrings": {
        "SomeContext": "SomeConnectionStringProperties"
      },
      "SectionOne": {
        "SectionOneTestVal": "SomeTestValue"
      }
    }
    

    In order to access the Test key, it would simply be @Configuration["Test"] while to access the SectionOneTestVal "key" in the SectionOne section, you would do something like Configuration.GetSection("SectionOne")["SectionOneTestVal"]:

    Thus adding this to a view:

    <p>@Configuration["Test"]</p>
    <p>@Configuration.GetSection("SectionOne")["SectionOneTestVal"]</p>
    

    ...would yield:

    Result

    For more information and examples, also check out dependency injection into views.