首页 > 解决方案 > 部署到 Azure 服务应用后 ConfigurationBuilder.Build() 中的字符串 Null

问题描述

我正在尝试将 .NET Core 2.1 应用程序部署到 Azure 服务应用程序。我能够在本地成功运行我的解决方案,但是当我将应用程序部署到 Azure 服务应用程序时,我在调用dotnet /home/site/wwwroot/MyApplication.dll应用程序时开始收到以下错误。

Unhandled Exception: System.ArgumentNullException: String reference not set to an instance of a String.
Parameter name: s
   at System.Text.Encoding.GetBytes(String s)
   at MyApplication.Startup.ConfigureServices(IServiceCollection services) in /home/vsts/work/1/s/MyApplication/Startup.cs:line 51
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at MyApplication.Program.Main(String[] args) in /home/vsts/work/1/s/MyApplication/Program.cs:line 23
   at MyApplication.Program.<Main>(String[] args)
bash: line 1:  1096 Aborted                 (core dumped) dotnet /home/site/wwwroot/MyApplication/MyApplication.dll

这似乎在方法内部的 Startup.cs 方法的第 51 行有一个空引用ConfigureServices。这与我构建配置的行相关,使用_configuration = builder.Build()


public IConfiguration _configuration { get; set; }

public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
    _configuration = configuration;
    _hostingEnvironment = hostingEnvironment;
}

public void ConfigureServices(IServiceCollection services)
{
    var builder = new ConfigurationBuilder()
                      .SetBasePath(_hostingEnvironment.ContentRootPath)
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddEnvironmentVariables();

    _configuration = builder.Build();  // this is line 51

    var appSettingsSection = _configuration.GetSection("AppSettings");
    ...
}

我唯一能想到的就是我的 appsettings.json 转换。在 dev 中,我指向我的开发服务器,在 prod 中,我指向生产。因此,在构建之后,我设置了一个文件转换来进行此更改。

但是,我已经从应用服务中提取了生成的 appsettings.json,将其插入到我的本地 appsettings.json 中,它仍然可以正常编译和运行。

这是正在部署的 appsettings.json。除了服务器名称和用户名/密码字符串之外,它完全相同。

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AppSettings": {
    "SecretKey": "MySecretKey",
    "SuperAdminEmail": "myemail@domain.com"
  },
  "ConnectionStrings": {
    "AuthDatabase": "Server=prod.mydomain.com;Database=Authentication;User Id=myUser;Password=Password1!;TrustServerCertificate=true"
  },
  "AllowedHosts": "*"
}

我看不出是什么原因造成的。我尝试将其部署到 AWS Lightsail Ubuntu 18.04 实例以查看是否可行。有时我会遇到同样的错误,但是,在多次尝试终止服务、重新启动服务器和其他项目之后,我让它运行了 10 分钟,然后再次崩溃。

我不擅长日志记录,尤其是在 Azure App Services 上……我怎样才能追踪 WHAT 字符串是否为空,以及我可以做些什么来验证它是否具有任何必要的值?

标签: c#azureasp.net-coreazure-web-app-service

解决方案


正如您在评论中提到的,_hostingEnvironment.ContentrootPathAppService 上的值为“ /home”,这是由于 AppService 引用的路径错误,您的应用程序无法读取某些内容的问题。

您可以按照此SO 帖子更改您的 ContentRootPath ,并根据您的要求相应地选择方法。


推荐阅读