How to read settings from appsettings.json in a view?
Hi forum,
I have Googled and tried (with only errors), so now I ask here. :)
In a view I want to read some values from appsettings.json. I have found some code that seems to be part of the solution:
MrAppsettings.cs:
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration.Models;
namespace MrAppsettings
{
public class SomeClass
{
private GlobalSettings _globalSettings;
public SomeClass(IOptions<GlobalSettings> globalSettings)
{
_globalSettings = globalSettings.Value;
var smtpHost = _globalSettings.Smtp.Host;
}
}
}
1) As I can read this must be registered in Startup.cs, but how?
2) And how do I "call" the class in my cshtml views?
Just to update this, personally I would inject a service. Look at @inject directive, creating a helper class that reads from the appSettings. This is referred to as "using dependency injection in a view" and you can read more about it in the Microsoft's Learn documentation.
How to read settings from appsettings.json in a view?
Hi forum,
I have Googled and tried (with only errors), so now I ask here. :)
In a view I want to read some values from appsettings.json. I have found some code that seems to be part of the solution:
MrAppsettings.cs:
1) As I can read this must be registered in Startup.cs, but how?
2) And how do I "call" the class in my cshtml views?
What you're doing here is DI. This is (a small) part of the solution.
Example:
Your appsettings.json:
Register the service (so you can do DI) in startup.cs:
Settings Class:
Class, constructor and usage:
Just to update this, personally I would inject a service. Look at @inject directive, creating a helper class that reads from the appSettings. This is referred to as "using dependency injection in a view" and you can read more about it in the Microsoft's Learn documentation.
is working on a reply...