【发布时间】:2022-01-23 09:57:17
【问题描述】:
我想在类库中的静态类中使用 appsettings.json 值 现在我知道如何像这样将 json 值绑定到 program.cs 中的类
程序.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;
}
}
如何在静态类中使用绑定的 APConfig?
我找到了解决办法:
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;
}
}
然后使用
HttpContext.Current.Session.SetString(key, value);
HttpContext.Current.Session.GetString(key);
【问题讨论】:
-
你的类不应该是静态的。
-
所以我都应该使用 DI 来代替?
-
是的,然后将 IConfiguration 注入到你的类中。
-
您可以使用静态方法,如果您从 DI 检索
APConfig实例并将其传递给该方法。Services.Configure<APConfig>将APConfig注册为具有 DI 的服务,并指定其属性应从IConfiguration中的设置填充,无论它们来自何处 - 而不仅仅是appsettings.json。这用于更容易生成依赖于设置对象的服务
标签: c# blazor class-library .net-6.0