【发布时间】:2018-11-13 23:32:42
【问题描述】:
我有一个带有 Razor 页面的 ASP.NET Core 2.1 Web 应用程序,它在 appsettings.json 文件中定义了 AAD 身份验证信息(由默认应用程序模板提供 - 请参阅下文,了解我是如何到达那里的)。但是,当尝试在Startup.cs 中配置身份验证时,配置中没有我的appsettings.json 中的任何配置值。如果我在调试器中检查 IConfiguration 对象,那么它似乎只有环境变量配置:
这是问题所在的Startup.ConfigureServices 方法:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options =>
{
// This is from the default template. It should work, but the relevant settings aren't there so options isn't populated.
this.Configuration.Bind("AzureAd", options);
// This of course works fine
options.Instance = "MyInstance";
options.Domain = "MyDomain";
options.TenantId = "MyTenantId";
options.ClientId = "MyClientId";
options.CallbackPath = "MyCallbackPath";
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
以及重要的服务配置(请注意,这是在服务结构无状态服务之上构建的):
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new ServiceInstanceListener[]
{
new ServiceInstanceListener(serviceContext =>
new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
return new WebHostBuilder()
.UseKestrel(opt =>
{
int port = serviceContext.CodePackageActivationContext.GetEndpoint("ServiceEndpoint").Port;
opt.Listen(IPAddress.IPv6Any, port, listenOptions =>
{
listenOptions.UseHttps(GetCertificateFromStore());
listenOptions.NoDelay = true;
});
})
.ConfigureServices(
services => services
.AddSingleton<StatelessServiceContext>(serviceContext))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseUrls(url)
.Build();
}))
};
}
为了创建这个服务,我使用了 VS2017 中的向导。我选择了一个现有的服务结构项目 (.sfproj) 并选择了 Services > Add > New Service Fabric Service 并选择了 Stateless ASP.NET Core [for .NET Framework],然后在下一页上我选择了 Web Application(带有 Razor Pages,而不是 MVC 的那个)并单击了 Change Authentication选择 Work or School Accounts 并输入我的 AAD 信息。我对此模板所做的唯一更改是在Startup.ConfigureServices 中的AddAzureAD 调用中添加代码,并将appsettings.json 文件设置为始终复制到输出目录。
为什么appsettings.json 文件没有加载到配置中?据我了解,这应该是默认发生的,但似乎缺少一些东西......
【问题讨论】:
-
WebHostBuilder默认不加载appsettings.json,需要手动调用AddJsonFile。 -
好吧,我会被诅咒的。果然,这解决了我的问题。我实际上并没有这样做,而是用
WebHost.CreateDefaultBuilder()替换了new WebHostBuilder(),但是为什么模板不能开箱即用是我无法理解的。谢谢! -
是的,这也会加载配置。我相信这是 2.0 的变化,也许你的模板是旧的?
-
有可能。谁知道模板最后一次更新是什么时候,但它们显然没有经过非常彻底的测试
标签: c# asp.net asp.net-core