gpt4 book ai didi

c# - 从 appsettings.json 文件中读取会出现 NullReferance 错误

转载 作者:太空宇宙 更新时间:2023-11-03 12:51:56 25 4
gpt4 key购买 nike

我正在尝试从我的 appsettings.json 文件中读取一些设置,但收到了 NullReferenceException。使用不同的 SO 帖子以及我在 google 上找到的一些博客,我构建了代码,一切似乎都是正确的,没有编译错误,intillisense 一切正常,所以我不确定我错过了什么或做错了什么。

Startup.CS:

public class Startup
{
public IConfigurationRoot Configuration { get; set; }

public Startup(IHostingEnvironment env)
{
//Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();

Configuration = builder.Build();
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCaching();
services.Configure<ApplicationSettingsModel>(Configuration.GetSection("AppSettings"));
services.AddScoped<IApplicationSettings, ApplicationSettings>();

services.AddSession(o =>
{
o.IdleTimeout = TimeSpan.FromSeconds(10);
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseExceptionHandler("/Error/ServerError");
app.UseIISPlatformHandler();
app.UseSession();
app.UseStaticFiles();
app.UseStatusCodePagesWithReExecute("/Error/PageNotFound");
app.UseMvc();
}

// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

I应用程序设置:

public interface IApplicationSettings
{
IOptions<ApplicationSettingsModel> AppSettings { get; }
}

ApplicationsSettings.cs:

public class ApplicationSettings : IApplicationSettings
{
protected readonly IOptions<ApplicationSettingsModel> _AppSettings;

public ApplicationSettings(IOptions<ApplicationSettingsModel> AppSettings)
{
_AppSettings = AppSettings;
}

public IOptions<ApplicationSettingsModel> AppSettings
{
get
{
return _AppSettings;
}
}

public string GetAppVersion()
{
return _AppSettings.Value.AppVersion;
}
}

型号:

public class ApplicationSettingsModel
{
public string AppVersion { get; set; }
public string BugZillaAPIKey { get; set; }
public string EmailUser { get; set; }
public string EmailPass { get; set; }
}

调用类:

public class EHAL
{
private static IApplicationSettings _config;

public EHAL(IApplicationSettings config)
{
_config = config;
}

public static string Test()
{
return _config.AppSettings.Value.AppVersion;
}
}

当我尝试运行 return _AppSettings.Value.AppVersion; 时出现错误。从 SO 帖子和博客来看,我认为我做的一切都是正确的,但显然我搞砸了,只是不确定是什么。

最佳答案

我不是 100% 确定你到底想做什么,但你应该能够让 DI 容器处理构造函数注入(inject),我做了一个小测试应用程序来注入(inject) test例如将类放入 Controller 中....

将您的测试类更改为

public class test : Itest
{
protected readonly IOptions<AppSettings> _AppSettings;

public test(IOptions<AppSettings> AppSettings)
{
_AppSettings = AppSettings;
}

public IOptions<AppSettings> AppSettings
{
get
{
return _AppSettings;
}
}

public string GetAppVersion()
{
return _AppSettings.Value.AppVersion;
}
}

添加接口(interface)Itest

public interface Itest
{
IOptions<AppSettings> AppSettings { get; }
}

在您的 Startup.cs 中添加一个新行

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddScoped<Itest, test>();

现在在您的 Controller 中,您可以执行以下操作:

 public class HomeController : Controller
{
private readonly Itest _config;
public HomeController(Itest config)
{
_config = config;
}
public IActionResult Index()
{
var a = _config.AppSettings.Value.AppVersion;
return View();
}
}

这只会将您的测试类实例注入(inject) Controller ,以便您可以在处理请求期间使用它。

同样,您不能 100% 确定您要使用它,这是一个如何让它发挥作用的示例。希望对您有所帮助!

编辑:你还有其他一些选择,你可以只注入(inject) IOptions<AppSettings>进入 Controller 构造函数并创建一个传入注入(inject)的测试类的实例 IOptions<AppSettings>以及。这样你就可以摆脱 Itest 接口(interface)和 Startup.cs 中的额外配置代码,这只是另一个想法。

编辑:所以,我真的认为你应该看看依赖注入(inject),它真的是要走的路。但是如果你真的不想去 DI 根,你可以这样做,(改变你的静态类看起来像这样):

public class test
{
static IConfigurationSection _Settings;

static test()
{

IConfiguration _config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

_Settings = _config.GetSection("AppSettings");
}

public static string GetAppVersion()
{
return _Settings["AppVersion"];
}
}

然后你可以这样调用:

var a = test.GetAppVersion();

虽然我不太喜欢用静力学来做这件事,但我试图保持你正在尝试做的事情的精神。确实,DI 是前进的方式,强烈建议您将来朝这个方向前进。

关于c# - 从 appsettings.json 文件中读取会出现 NullReferance 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com