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

如何通过Program/Startup.cs实现MainTestAPI联动启动子API并映射路径?

解决方案

一、自动启动子API服务

在MainTestAPI的Program.cs中添加启动逻辑,可根据开发/生产环境选择不同的启动方式:

开发环境(本地调试)

直接调用dotnet run启动子项目,示例代码:

using System.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

// 定义子项目名称和相对路径(根据实际结构调整)
var subProjects = new List<(string Name, string ProjectPath)>
{
    ("Test1", "../Test1"),
    ("Test2", "../Test2"),
    ("Test3", "../Test3")
};

foreach (var (name, path) in subProjects)
{
    var startInfo = new ProcessStartInfo
    {
        FileName = "dotnet",
        Arguments = $"run --project {path}",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true
    };

    var process = Process.Start(startInfo);
    // 可选:捕获子项目日志输出
    process.OutputDataReceived += (_, e) => !string.IsNullOrEmpty(e.Data) && Console.WriteLine($"[{name}] {e.Data}");
    process.ErrorDataReceived += (_, e) => !string.IsNullOrEmpty(e.Data) && Console.WriteLine($"[{name}] ERROR: {e.Data}");
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
}

// 常规服务注册
builder.Services.AddControllers();

var app = builder.Build();

// 中间件配置
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

生产环境

若子API已发布为独立可执行文件,直接启动对应exe:

var subServices = new List<(string Name, string ExePath)>
{
    ("Test1", "./Test1/Test1.exe"),
    ("Test2", "./Test2/Test2.exe"),
    ("Test3", "./Test3/Test3.exe")
};

foreach (var (name, path) in subServices)
{
    var startInfo = new ProcessStartInfo
    {
        FileName = path,
        UseShellExecute = false,
        CreateNoWindow = true
    };
    Process.Start(startInfo);
}

二、请求路径映射(反向代理)

推荐使用官方的YARP反向代理中间件,比手动URL重写更稳定易维护:

1. 安装YARP包

在MainTestAPI项目中执行NuGet安装命令:

Install-Package Yarp.ReverseProxy

2. 配置代理规则

在appsettings.json中添加路由和集群配置:

"ReverseProxy": {
  "Routes": {
    "Test1Route": {
      "ClusterId": "Test1Cluster",
      "Match": {
        "Path": "/api/Test1/{**catch-all}"
      },
      "Transforms": [
        { "PathRemovePrefix": "/api/Test1" }
      ]
    },
    "Test2Route": {
      "ClusterId": "Test2Cluster",
      "Match": {
        "Path": "/api/Test2/{**catch-all}"
      },
      "Transforms": [
        { "PathRemovePrefix": "/api/Test2" }
      ]
    },
    "Test3Route": {
      "ClusterId": "Test3Cluster",
      "Match": {
        "Path": "/api/Test3/{**catch-all}"
      },
      "Transforms": [
        { "PathRemovePrefix": "/api/Test3" }
      ]
    }
  },
  "Clusters": {
    "Test1Cluster": {
      "Destinations": {
        "Test1": { "Address": "http://localhost:5001" } // 替换为Test1的实际端口
      }
    },
    "Test2Cluster": {
      "Destinations": {
        "Test2": { "Address": "http://localhost:5002" } // 替换为Test2的实际端口
      }
    },
    "Test3Cluster": {
      "Destinations": {
        "Test3": { "Address": "http://localhost:5003" } // 替换为Test3的实际端口
      }
    }
  }
}

3. 注册并启用YARP

在Program.cs中添加代理服务注册和中间件:

var builder = WebApplication.CreateBuilder(args);

// 注册YARP代理并加载配置
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

// 其他服务注册...

var app = builder.Build();

// 启用代理中间件(需放在路由相关中间件之前)
app.UseReverseProxy();

// 其他中间件配置...
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

注意事项

  • 子API需设置固定端口(修改各自的launchSettings.json),避免端口变动导致代理失效。
  • 生产环境建议用专门的进程管理工具(如Systemd、NSSM)托管子API,而非依赖MainTestAPI启动,提升稳定性。
  • 若不想用YARP,也可自定义中间件实现转发,但需手动处理请求头、响应流等细节,复杂度较高。

内容的提问来源于stack exchange,提问作者Vasu V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 22:40:58