Yiyi You's answer is appropriate for when your value is under a section. But if your value is directly under the root of appsettings.json
, for example:
{
...
"MyValueAtRoot" : "value"
}
Then you need to call it from your view using:
@Configuration.GetValue(typeof(string), "MyValueAtRoot")
An additional interesting fact: The GetValue
method has a generic overload method, but the returned value of such methods can't be rendered directly as html because the generic type parameter gets confused with plain html.
If you really want to use that method, you would first have to store the returned value in a variable, inside a razor code block, like this:
@{ var myValue = Configuration.GetValue<string>("MyValueAtRoot"); }
Then later render the variable:
<p>@myValue</p>
Note: For both of my examples, you also need the call the @using
and @inject
directives first, as described in the accepted answer.
appsettings.json
usually contains sensitive information, which should not be printed in a webpage or api response. It's a really bad idea... – Antimalarial