c# – ASP.NET Core Web服务不会将appsettings.json加载到配置中

前端之家收集整理的这篇文章主要介绍了c# – ASP.NET Core Web服务不会将appsettings.json加载到配置中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有Razor Pages的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>添加>新的Service Fabric Service并选择了Stateless ASP.NET Core [for .NET Framework],然后在下一页我选择了Web Application(Razor Pages,而不是MVC)并点击了Change Authentication,我选择了Work或School Accounts并输入了我的AAD信息.我对此模板所做的唯一更改是在Startup.ConfigureServices中调用AddAzureAD中的代码,并将appsettings.json文件设置为始终复制到输出目录.

为什么appsettings.json文件没有加载到配置中?据我了解,这应该默认发生,但似乎缺少某些东西……

解决方法

WebHostBuilder默认不加载appsettings.json,您需要手动调用AddJsonFile.例如:
return new WebHostBuilder()
            .UseKestrel(opt =>
            {
                //snip
            })
            .ConfigureAppConfiguration((builderContext,config) =>
            {
                config.AddJsonFile("appsettings.json",optional: false);
            })
            .ConfigureServices(
                services => services
                    .AddSingleton<StatelessServiceContext>(serviceContext))
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseServiceFabricIntegration(listener,ServiceFabricIntegrationOptions.None)
            .UseUrls(url)
            .Build();

或者,您可以使用WebHost.CreateDefaultBuilder,这将加载更多默认值.

原文链接:https://www.f2er.com/netcore/239110.html

猜你在找的.NET Core相关文章