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

添加测试后Azure上的C#后端API启动失败(500.30错误)

问题描述

我正在为React天气应用开发部署在Azure上的C#后端,该后端负责从数据库获取用户数据并调用API获取天气数据。原本后端运行正常,添加与后端服务同级的Tests文件夹(基于Xunit编写控制器测试,示例代码如下)后,本地测试全部通过,Swagger调用也正常。但将测试代码推送到关联Azure的GitHub仓库后,通过Azure API管理服务调用接口时返回HTTP Error 500.30 - ASP.NET Core应用启动失败错误。删除GitHub中的Tests文件夹后API恢复正常,但需要保留测试以获取Codecov报告,求解决方法。

测试示例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using stin_backend.Controllers;
using stin_backend.Models;
using Xunit;

namespace Tests.Controller
{
    public class UserControllerTest
    {
        private readonly DbContextOptions<DatabaseContext> _dbContextOptions;

        public UserControllerTest()
        {
            _dbContextOptions = new DbContextOptionsBuilder<DatabaseContext>()
                .UseInMemoryDatabase(databaseName: "UsersControllerTests")
                .Options;
        }

        [Fact]
        public async Task GetUser_ShouldReturnAllUsers()
        {
            // Arrange
            var dbContextOptions = new DbContextOptionsBuilder<DatabaseContext>()
                .UseInMemoryDatabase(databaseName: "TestDatabase")
                .Options;

            using (var context = new DatabaseContext(dbContextOptions))
            {
                if (!context.User.Any(u => u.id == 1))
                {
                    context.User.Add(new User { id = 1, username = "John", password = "password", pay = "100" });
                }

                if (!context.User.Any(u => u.id == 2))
                {
                    context.User.Add(new User { id = 2, username = "Jane", password = "password", pay = "200" });
                }

                context.SaveChanges();

                var controller = new UsersController(context);

                // Act
                var result = await controller.GetUser();

                // Assert
                result.Value.Should().BeAssignableTo<IEnumerable<User>>();

                var users = result.Value as IEnumerable<User>;
                users.Should().HaveCount(2);
                users.Should().ContainEquivalentOf(
                    new User { id = 1, username = "John", password = "password", pay = "100" },
                    options => options.ExcludingMissingMembers()
                );
                users.Should().ContainEquivalentOf(
                    new User { id = 2, username = "Jane", password = "password", pay = "200" },
                    options => options.ExcludingMissingMembers()
                );
            }
        }
        // 其他测试方法...
}
解决方案

1. 配置Azure部署,仅编译主项目

Azure默认会编译整个解决方案的所有项目,测试项目的依赖或配置可能干扰生产环境启动。

  • 在Azure App Service的部署中心,修改构建命令为仅编译后端主项目:
    dotnet publish stin_backend/stin_backend.csproj -c Release
    
  • 或者在解决方案根目录添加.deployment文件,指定部署目标项目:
    [config]
    project = stin_backend/stin_backend.csproj
    
    这样部署流程只会处理主项目,测试代码不会被打包到Azure环境。

2. 隔离测试项目的依赖与配置

测试项目引入的FluentAssertions、Xunit等依赖,或测试配置文件可能与生产环境冲突:

  • 编辑测试项目的.csproj文件,确保测试配置文件不会被复制到输出目录:
    <ItemGroup>
      <Content Remove="appsettings.json" />
      <None Include="appsettings.json">
        <CopyToOutputDirectory>Never</CopyToOutputDirectory>
      </None>
    </ItemGroup>
    
  • 检查测试代码中是否有全局初始化逻辑(如静态构造函数),这类代码可能在部署后被意外执行,需确保测试逻辑仅在测试运行时触发。

3. 查看Azure启动日志定位具体错误

500.30是泛型错误,需要获取详细日志排查:

  • 登录Azure门户,进入目标App Service,在监控>日志流中查看实时启动日志,找到具体异常信息(如依赖缺失、配置错误等)。
  • 或通过高级工具>Kudu访问D:\home\LogFiles\Application目录,查看stdout日志文件,获取启动失败的堆栈信息,针对性修复。

4. 用GitHub Actions拆分测试与部署流程

如果用GitHub Actions触发Azure部署,可将测试和部署拆分为独立步骤:

  • 第一步在GitHub运行环境中执行测试并生成Codecov报告,无需将测试代码打包。
  • 第二步仅编译部署主项目到Azure。
    示例工作流片段:
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: 8.0.x
      - name: Restore dependencies
        run: dotnet restore
      - name: Run tests & collect coverage
        run: dotnet test Tests/Tests.csproj --collect:"XPlat Code Coverage"
      - name: Upload to Codecov
        uses: codecov/codecov-action@v4

  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: 8.0.x
      - name: Publish main project
        run: dotnet publish stin_backend/stin_backend.csproj -c Release -o publish
      - name: Deploy to Azure
        uses: azure/webapps-deploy@v3
        with:
          app-name: your-app-service-name
          publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
          package: ./publish

内容的提问来源于stack exchange,提问作者Jan Sodomka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:47:34