0

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.

  • Can you link the tutorials you are talking about? Have you also seen [this](https://stackoverflow.com/questions/48979294/how-to-read-appsettings-json-in-my-layout-chtml)? – Timothy G. Jun 02 '21 at 18:31
  • None of that makes sense/works. What is ApplicationInsights, I put those using/inject at the top of the .cshtml and did this `@Configuration.GetSection("ApplicationInsights")["MyKey"];` and that's empty (displays nothing on the page). –  Jun 02 '21 at 18:46

1 Answers1

0

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.

Timothy G.
  • 6,335
  • 7
  • 30
  • 46