不确定我在这里错过了什么,但我无法从我的应用程序设置中获得值。Json在我的。net核心应用程序。我有我的appsettings。json:
{
"AppSettings": {
"Version": "One"
}
}
启动:
public class Startup
{
private IConfigurationRoot _configuration;
public Startup(IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder()
}
public void ConfigureServices(IServiceCollection services)
{
//Here I setup to read appsettings
services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
}
}
模型:
public class AppSettings
{
public string Version{ get; set; }
}
控制器:
public class HomeController : Controller
{
private readonly AppSettings _mySettings;
public HomeController(IOptions<AppSettings> settings)
{
//This is always null
_mySettings = settings.Value;
}
}
_mySettings总是空的。我是不是遗漏了什么?
我在WPF中遇到了类似的问题。NET Framework 5.0)
我所要做的就是登记。
services.AddSingleton<IConfiguration>(_configuration);
配置本身是这样配置的(在App.xaml.cs中):
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
_configuration = builder.Build();
这通常发生在vscode中,因为配置launch.json的方式不同。
基于这个答案,我不得不重新配置基本路径,配置正在搜索的DLL的路径,因为默认设置是可选的,很难在.net core 3.1和net 5.0应用程序中追踪到这一点。以下是我如何重新配置的
Program.cs:
using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace API
{
public class Program
{
public static int Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
return 0;
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(c =>
{
var codeBase = Assembly.GetExecutingAssembly().Location;
var uri = new UriBuilder(codeBase);
var path = Uri.UnescapeDataString(uri.Path);
var assembyDirectory = Path.GetDirectoryName(path);
c.SetBasePath(assembyDirectory);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
;
}
}
}
我可以在Startup.cs中访问配置:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model;
namespace API
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var myOptions = Configuration.To<ApiConfig>();
services.AddAuthentication(myOptions.Secret);
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}