Can';t在asp.net mvc 6 beta 8中检索应用程序设置
我正试图创建一个新的ASP.NETMV5项目(目前为beta8),以供学习之用 我一直在处理获取应用程序设置的简单案例 我在appsettings.json文件中添加了一些配置:Can';t在asp.net mvc 6 beta 8中检索应用程序设置,asp.net,dependency-injection,asp.net-core-mvc,Asp.net,Dependency Injection,Asp.net Core Mvc,我正试图创建一个新的ASP.NETMV5项目(目前为beta8),以供学习之用 我一直在处理获取应用程序设置的简单案例 我在appsettings.json文件中添加了一些配置: { "Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-someproject-e84e86e2-0fec-4132-9a91-2f6c4b4c
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-someproject-e84e86e2-0fec-4132-9a91-2f6c4b4c61a3;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
"AppSettings": {
"CloudStorageContainerReference": "someproject",
"StorageConnectionString": "UseDevelopmentStorage=true"
}
}
我还创建了一个强类型类:
public class AppSettings
{
public string CloudStorageContainerReference { get; set; }
public string StorageConnectionString { get; set; }
}
并更新了我的启动文件:
public void ConfigureServices(IServiceCollection services)
{
// Add Entity Framework services to the services container.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add settings
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Add MVC services to the services container.
services.AddMvc();
// Register application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
但是它抛出一个NullReferenceException
,因为我的appSettings
参数为null
少了什么
[编辑]:作为旁注,这一行:
Configuration["AppSettings:CloudStorageContainerReference"]
返回正确的单个值。不确定原因,但我通过将类成员“AppSettings”重命名为“Settings”并展开IOPS解决了此问题:
public class TransfertController : Controller
{
private readonly AppSettings Settings;
public TransfertController(IOptions<AppSettings> settings)
{
if (settings == null) throw new ArgumentNullException(nameof(settings));
Settings = settings.Value;
}
}
公共类传输控制器:控制器
{
私有只读应用程序设置;
公共传输控制器(IOptions设置)
{
如果(settings==null)抛出新的ArgumentNullException(nameof(settings));
设置=设置.值;
}
}
正在工作…我想说这只是您原始代码中的一个输入错误:
public TransfertController(IOptions<AppSettings> appSettings)
{
if (AppSettings == null) throw new ArgumentNullException(nameof(settings));
AppSettings = appSettings;
}
公共传输控制器(IOOptions appSettings)
{
如果(AppSettings==null)抛出新的ArgumentNullException(nameof(settings));
AppSettings=AppSettings;
}
在guard中,您正在检查正在分配的相同属性AppSettings
,然后再对其进行分配。如果(appSettings==null)抛出new…(注意小写的appSettings),您希望警卫检查方法输入参数,而不是属性
public TransfertController(IOptions<AppSettings> appSettings)
{
if (AppSettings == null) throw new ArgumentNullException(nameof(settings));
AppSettings = appSettings;
}