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

.NET6迁移.NET8后Azure Function Http Trigger无响应返回500错误

问题概述

将Azure Function通过dotnet-isolated worker从.NET 6迁移至.NET 8后,控制台显示服务无错误运行,但调用Http Trigger时函数未被触发,超时后返回500状态码且无错误响应;Postman调用时出现Error: read ECONNRESET错误。已移除Startup类并创建Program类用于Host Builder和依赖注入,但控制台仍提及已删除的Startup类。

提供的相关代码

项目文件代码

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <AzureFunctionsVersion>v4</AzureFunctionsVersion>
        <OutputType>Exe</OutputType>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>
    
    <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
        <PackageReference Include="Azure.Identity" Version="1.10.4" />
        <PackageReference Include="Microsoft.Azure.AppConfiguration.Functions.Worker" Version="7.1.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.1.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.17.2" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.21.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="1.2.1" />
        <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.2.0" />
    </ItemGroup>
    <ItemGroup>
        <None Update="host.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Update="local.settings.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
            <CopyToPublishDirectory>Never</CopyToPublishDirectory>
        </None>
    </ItemGroup>
    <ItemGroup>
        <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
    </ItemGroup>
    
</Project>

Program类代码

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureAppConfiguration(builder =>
    {
        string AppConfigurationConnection = Environment.GetEnvironmentVariable("AppConfig");
        builder.AddAzureAppConfiguration(options =>
        {
            options.Connect(new Uri(AppConfigurationConnection), new DefaultAzureCredential())
            .ConfigureKeyVault(kv =>
            {
                kv.SetCredential(new DefaultAzureCredential());
            })
            .Select("*")
            .ConfigureRefresh(refresh =>
            {
                refresh.Register("Control", refreshAll: true)
                .SetCacheExpiration(new TimeSpan(0, 0, 30));
            });
        });
    })
    .ConfigureServices(services =>
    {
        // If using Kestrel:
        services.Configure<KestrelServerOptions>(options =>
        {
            options.AllowSynchronousIO = true;
        });

        // If using IIS:
        services.Configure<IISServerOptions>(options =>
        {
            options.AllowSynchronousIO = true;
        });

        services.AddAzureAppConfiguration();
        services.AddOptions<AzureAppConfigSettings>()
                        .Configure<IConfiguration>((settings, configuration) =>
                        {
                            configuration.GetSection("value").Bind(settings);
                        });
        services.AddHttpClient();
        services.AddSingleton<CommonService>();

    })
    .Build();

await host.RunAsync();

Postman错误信息

Error: read ECONNRESET
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.37.0
Accept: */*
Postman-Token: 80bafe6e-83f3-4d92-9013-ece684c7c610
Host: localhost:7071
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
排查与解决方案
  • 清理Startup类残留引用

    1. 检查项目目录下是否还存在Startup.cs文件,如有则彻底删除;
    2. 打开local.settings.json和host.json,确认没有任何指向Startup类的配置项;
    3. 删除项目的bin和obj目录,重新生成项目,避免旧编译文件的残留影响。
  • 修复Azure App Configuration初始化问题

    1. 检查local.settings.json中AppConfig环境变量是否正确配置,确保其值不为空;
    2. 在Program类的配置代码中添加异常捕获,暴露初始化过程中的错误:
      try
      {
          string AppConfigurationConnection = Environment.GetEnvironmentVariable("AppConfig");
          if (string.IsNullOrEmpty(AppConfigurationConnection))
          {
              throw new InvalidOperationException("未设置AppConfig环境变量");
          }
          builder.AddAzureAppConfiguration(options =>
          {
              // 原有配置代码
          });
      }
      catch (Exception ex)
      {
          Console.WriteLine($"Azure App Configuration初始化失败: {ex.Message}");
          throw;
      }
      
  • 验证Http Trigger函数实现
    确保函数使用dotnet-isolated模式的正确注解和返回类型,示例如下:

    public class HttpTriggerFunction
    {
        [Function("MyHttpTrigger")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req, FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("MyHttpTrigger");
            logger.LogInformation("触发Http函数");
            
            var response = req.CreateResponse(System.Net.HttpStatusCode.OK);
            response.WriteString("来自.NET 8隔离模式函数的响应");
            return response;
        }
    }
    
  • 检查host.json配置
    确保host.json中指定了正确的worker运行时:

    {
        "version": "2.0",
        "workerRuntime": "dotnet-isolated",
        "logging": {
            "applicationInsights": {
                "samplingSettings": {
                    "isEnabled": true,
                    "excludedTypes": "Request"
                }
            }
        }
    }
    
  • 排查端口占用问题

    1. 检查localhost:7071是否被其他进程占用,可通过命令行netstat -ano | findstr :7071查看;
    2. 若端口被占用,修改local.settings.json中的端口号:
      {
          "Host": {
              "LocalHttpPort": 7072
          }
      }
      
    3. 重启Azure Functions Core Tools后再次测试。

内容的提问来源于stack exchange,提问作者Rajib Mahata

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:29:51