How can I use the appsettings.json in static class in net 6 class library

Viewed 1539

I want to use the appsettings.json value in static class which in class library now I know how to bind json value to class in program.cs like this

program.cs

ConfigurationManager configuration = builder.Configuration;
builder.Services.Configure<APConfig>(configuration.GetSection(APConfig.Position));

APConfig.cs

public class APConfig
{
    public const string Position = "APConfig";

    public string RootPath { get; set; }
    public string API_URL { get; set; }
    public string TOKEN { get; set; }
    public string pwdkey { get; set; }
    public string pwdkey1 { get; set; }
    public string pwdkey2 { get; set; }

    public string GetProperty(string keyStr)
    {
        string value = Utility.DecryptTagContent((string)this.GetType().GetProperty(keyStr).GetValue(this));

        return value;
    }
}

How can I use the binded APConfig in a static class?

I found a solution:

public static class HttpContext
{
    private static IHttpContextAccessor _accessor;

    public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;

    internal static void Configure(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
}

public static class StaticHttpContextExtensions
{
    public static void AddHttpContextAccessor(this IServiceCollection services)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
    {
        var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        HttpContext.Configure(httpContextAccessor);
        return app;
    }
}

then use

HttpContext.Current.Session.SetString(key, value);
HttpContext.Current.Session.GetString(key);
2 Answers

Accessing configuration requires an instance of IConfiguration which can be obtained using dependency injection.

Your class should then be non-static and have a DI constructor.

I also like to have static access to the configuration values.

This StackOverflow question has several answers that may be helpful: ASP.NET Core—access Configuration from static class

The key is that you need code that runs at startup that assigns the IConfiguration object or it's values to a static variable.

Then you can iterate over the values and place them in a static list. Something like public static List<KeyValuePair<string, string>> Config= _config.AsEnumerable().ToList(); Or you could place those values in a public static ReadOnlyDictionary<string, object>

Related