c# - 如何设置 IHostingEnvironment.ContentRootPath?

标签 c# azure-service-fabric asp.net-core-2.2

在我的 Azure Service Fabric Web API 项目中,我可以使用 Api.cs 类中的以下代码将 appsettings.json 文件添加到我的配置中:

    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()
                                .ConfigureAppConfiguration((builderContext, config) =>
                                {
                                        var env = builderContext.HostingEnvironment;
                                        config.SetBasePath(env.ContentRootPath)
                                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                                            .AddEnvironmentVariables();
                                })
                                .ConfigureServices((hostingContext, services) => services
                                .AddSingleton<StatelessServiceContext>(serviceContext)
                                .AddApplicationInsightsTelemetry(hostingContext.Configuration))
                                .UseContentRoot(Directory.GetCurrentDirectory())
                                .UseStartup<Startup>()
                                .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                                .UseUrls(url)
                                .Build();
                }))
        };
    }

env.ContentRootPath 包含此值:

C:\SfDevCluster\Data\_App\_Node_0\Abc.IntegrationType_App197\Abc.Integration.ApiPkg.Code.1.0.0

在此文件夹中,我可以看到 appsettings.json 文件。

但是,在我的 Azure Service Fabric 无状态服务项目中,我的 Service.cs 类中有以下代码:

    protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        Microsoft.AspNetCore.WebHost.CreateDefaultBuilder()
            .ConfigureAppConfiguration((builderContext, config) =>
            {
                var env = builderContext.HostingEnvironment;

                var appName = AppDomain.CurrentDomain.FriendlyName;
                var parentFolderPath = Directory.GetParent(env.ContentRootPath).FullName;
                var packageCodeFolderPath = Path.Combine(parentFolderPath, appName + "Pkg.Code.1.0.0");

                config.SetBasePath(packageCodeFolderPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();
            })
            .UseStartup<Startup>()
            .Build()
            .Run();
    }

此处 env.ContentRootPath 包含此值:

C:\SfDevCluster\Data\_App\_Node_0\Abc.Integration.OpticalType_App198\work

但是,因为 appsettings.json 文件位于: C:\SfDevCluster\Data\_App\_Node_0\Abc.Integration.OpticalType_App198\Abc.Integration.Optical.ServicePkg.Code.1.0.0

我被迫构造您在上面看到的packageCodeFolderPath变量。

这看起来不是一个非常优雅的解决方案,我担心 Pkg.Code.1.0.0 中的版本号可能会改变(如果这甚至是版本号?)。

如何将 env.ContentRootPath 设置为包含 appsettings.json 文件的文件夹路径?或者有更好的方法来访问这些文件吗?

最佳答案

在服务 list 中,您应将 WorkingFolder 设置为 CodePackage,以将 ContentRootPath 设置为代码 Abc.Integration.Optical.ServicePkg.Code。 1.0.0 而不是 work

即:

<EntryPoint>
  <ExeHost>
    <Program>myapp.exe</Program>
    <WorkingFolder>CodePackage</WorkingFolder>
  </ExeHost>
</EntryPoint>

查看文档 here

另一个选项是从 SF 设置的环境变量中获取信息。看看这里:https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-environment-variables-reference

或者,按照 Loek 在其回答中建议的方式使用 context.CodePackageActivationContext.WorkDirectory

关于c# - 如何设置 IHostingEnvironment.ContentRootPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822261/

相关文章:

azure - 无法找到 Service Fabric 应用程序 Visual Studio 2017 中的新项目选项

azure - 服务结构: packaging code error: missing required references

azure - 如何迁移 Azure Service Fabric 中的 Windows 服务

c# - ConfidentialClientApplication.AcquireTokenForClient().ExecuteAsync() 线程安全吗?

c# - 减少两个 foreach 循环中的执行时间

c# - 在不使用同步机制的情况下从 2 个不同的线程写入共享资源

javascript - 从 ASP.NET Core v2.2 WebAPI 应用程序发送响应 header

c# - Wcf 和接口(interface)作为参数

c# - 每次刷新都会增加更新私有(private) Observable Collection 的时间