You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6.0升级后Web Job无法读取应用设置求助

Web Job从.NET Framework 4.7.2升级到.NET 6.0后无法读取应用设置

问题说明

将Web Job从.NET Framework 4.7.2升级至.NET 6.0并更新依赖包后,作业无法识别Azure应用设置,仅在app.config中手动指定设置时才能正常运行。

该Web Job每5分钟执行一次,逻辑完成后调用Azure函数。升级过程中JobHostConfiguration已废弃,改用HostBuilder调整代码后,Web Job能检测到Azure函数,但部署后无法读取应用设置——比如代码中var clientId = ConfigurationManager.AppSettings["ClientId"];返回null,而该设置已在Azure应用配置中配置。

无法获取应用设置的代码片段

using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace CDP.Portal.Azure.WJCMTFileUpload
{
    public class Functions
    {
        /// <summary>
        /// 将客户列表转换为按POS分组的记录
        /// </summary>
        /// <returns></returns>
        [NoAutomaticTrigger]
        public static async Task RunFunction()
        {
            TelemetryClient appInsights = new TelemetryClient
            {
                InstrumentationKey = ConfigurationManager.AppSettings["AppInsights"]
            };

            try
            {
                var clientId = ConfigurationManager.AppSettings["ClientId"];

                if (clientId != null && !string.IsNullOrEmpty(clientId))
                {
                    string token = await CDP.Portal.Azure.Common.Common.AccessTokenGeneratorSecrets(
                        ConfigurationManager.AppSettings["ClientId"],
                        ConfigurationManager.AppSettings["ResourceUri"],
                        ConfigurationManager.AppSettings["KeyVaultSecretName"]);

                    CrmHelper._client = new HttpClient()
                    {
                        BaseAddress = new Uri(ConfigurationManager.AppSettings["ResourceApiUri"]),
                        DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", token) }
                    };
                }

                List<CustomerList> noteLists;

                string targetFilename = ConfigurationManager.AppSettings["targetFilename"];
                string nonoteRow = ConfigurationManager.AppSettings["nonoteRow"];

                if (string.IsNullOrEmpty(targetFilename))
                {
                    targetFilename = "CMT_";
                }

                try
                {
                    noteLists = await CrmHelper.GetNotesToProcess(appInsights, targetFilename, nonoteRow);
                }
                // 剩余代码省略
            }
            catch
            {
                // 异常处理省略
            }
        }
    }
}

已尝试的解决方法

  • 使用CloudConfigurationManager.GetSetting替代ConfigurationManager.AppSettings
  • 在AppSettings中配置configSource=

项目.csproj文件内容

<Project Sdk="Microsoft.NET.Sdk;Microsoft.NET.Sdk.Publish">
  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Compile Remove="Helpers\CrmHelper.cs" />
    <Compile Remove="Helpers\CsvHelper.cs" />
    <Compile Remove="Models\CustomerList.cs" />
    <Compile Remove="Models\Note.cs" />
    <Compile Remove="Models\OdataCollectionWrapper.cs" />
    <Compile Remove="Models\Pos.cs" />
    <Compile Remove="Models\TargetList.cs" />
    <Compile Remove="Models\Translation.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Remove="Helpers\CsvHelper.cs~RF130716c7.TMP" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="ClosedXML" Version="0.102.1" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.22.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="5.0.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Host.Storage" Version="5.0.0" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.3.0" />
    <PackageReference Include="RestSharp" Version="110.2.0" />
    <PackageReference Include="System.Spatial" Version="5.8.5" />
    <PackageReference Include="Microsoft.Data.Edm" Version="5.8.5" />
    <PackageReference Include="Microsoft.Data.OData" Version="5.8.5" />
    <PackageReference Include="Microsoft.Data.Services.Client" Version="5.8.5" />
    <PackageReference Include="Microsoft.WindowsAzure.ConfigurationManager" Version="3.2.3" />
    <PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Core" Version="3.0.39" />
    <PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.39" />
    <PackageReference Include="Microsoft.Azure.KeyVault.Core" Version="3.0.5" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="settings.job">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Helpers\" />
    <Folder Include="Models\" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\CDP.Portal.Azure.Common\CDP.Portal.Azure.Common.csproj" />
  </ItemGroup>
</Project>

解决方案

1. 改用.NET 6依赖注入获取配置

.NET 6 Web Job推荐通过IConfiguration依赖注入读取配置,替代旧的ConfigurationManager:

步骤1:重构函数类,注入配置

using Microsoft.Extensions.Configuration;
using Microsoft.ApplicationInsights;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace CDP.Portal.Azure.WJCMTFileUpload
{
    public class Functions
    {
        private readonly IConfiguration _configuration;
        private readonly TelemetryClient _appInsights;

        // 构造函数注入IConfiguration和TelemetryClient
        public Functions(IConfiguration configuration, TelemetryClient appInsights)
        {
            _configuration = configuration;
            _appInsights = appInsights;
        }

        [NoAutomaticTrigger]
        public async Task RunFunction()
        {
            try
            {
                var clientId = _configuration["ClientId"];

                if (!string.IsNullOrEmpty(clientId))
                {
                    string token = await CDP.Portal.Azure.Common.Common.AccessTokenGeneratorSecrets(
                        _configuration["ClientId"],
                        _configuration["ResourceUri"],
                        _configuration["KeyVaultSecretName"]);

                    CrmHelper._client = new HttpClient()
                    {
                        BaseAddress = new Uri(_configuration["ResourceApiUri"]),
                        DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", token) }
                    };
                }

                string targetFilename = _configuration["targetFilename"] ?? "CMT_";
                string nonoteRow = _configuration["nonoteRow"];

                var noteLists = await CrmHelper.GetNotesToProcess(_appInsights, targetFilename, nonoteRow);
                // 剩余逻辑保持不变
            }
            catch
            {
                // 异常处理
            }
        }
    }
}

步骤2:配置HostBuilder加载环境变量

修改Program.cs,确保HostBuilder正确加载Azure应用设置(Azure应用设置会以环境变量形式注入):

using Microsoft.Extensions.Hosting;
using Microsoft.Azure.WebJobs;

namespace CDP.Portal.Azure.WJCMTFileUpload
{
    class Program
    {
        static void Main()
        {
            var host = new HostBuilder()
                .ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    // 添加其他所需扩展
                })
                .ConfigureAppConfiguration((context, config) =>
                {
                    // 加载环境变量(包含Azure应用设置)
                    config.AddEnvironmentVariables();
                    // 本地调试时可加载appsettings.json
                    if (context.HostingEnvironment.IsDevelopment())
                    {
                        config.AddJsonFile("appsettings.json", optional: true);
                    }
                })
                .Build();

            using (host)
            {
                host.Run();
            }
        }
    }
}

2. 统一依赖包版本

当前项目中Microsoft.Azure.WebJobs(3.0.39)与Microsoft.Azure.WebJobs.Extensions(5.0.0)版本不兼容,建议统一版本:

  • 若保留3.x系列,将Microsoft.Azure.WebJobs.Extensions降级至3.0.18
  • 若升级至4.x系列,将相关包统一更新为4.x版本,例如:
<PackageReference Include="Microsoft.Azure.WebJobs" Version="4.1.3" />
<PackageReference Include="Microsoft.Azure.WebJobs.Core" Version="4.1.3" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" />

3. 确认Azure应用设置配置

登录Azure门户,进入Web Job所属的App Service,检查配置 > 应用程序设置中是否已正确添加ClientId、AppInsights等所有所需设置,确保部署后未被覆盖。


内容的提问来源于stack exchange,提问作者EL MASLOUHI HAMZA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:16:02