加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:15:11 所属栏目:百科 来源:网络整理
导读:我有一个带有Razor Pages的ASP.NET Core 2.1 Web应用程序,它具有在appsettings.json文件中定义的AAD身份验证信息(由默认应用程序模板提供 – 请参阅下面我如何到达那里).但是,在尝试在Startup.cs中配置身份验证时,配置中没有来自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,这将加载更多默认值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读