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

C# Minimal API多代理实例程序化启动端口参数不生效问题

问题根因

参数传递格式错误是核心原因。
你在代码中将--urls和对应的监听地址拼接成了单个字符串传入ArgumentList,dotnet运行时会将整段字符串识别为一个独立参数,无法解析出--urls配置项对应的取值,因此Minimal API会回退到默认监听端口5000,第二个实例启动时自然会因为5000端口被占用崩溃。
手动在PowerShell执行命令时,PowerShell会自动按空格拆分命令段,将--urls和监听地址拆分为两个独立参数传给dotnet进程,因此手动启动可以正常绑定指定端口。
另外你现有代码在进程启动后立刻调用Kill()方法,进程刚完成初始化就被强制终止,根本无法正常对外提供服务。

修复方法
  1. 将--urls和监听地址拆分为两个独立参数添加到ArgumentList,不要拼接成单个字符串
  2. 删除启动后立即执行的进程杀死逻辑,在需要统一停止实例的时候再做终止操作
  3. 批量启动100个实例直接通过循环遍历端口段实现即可,无需为每个实例单独编写启动代码

修复后的可直接运行的代码示例:

using System.Diagnostics;

string workingDir = @"C:\StartAgent\StartAgent\StartAgent\bin\Debug\net6.0";
string dllPath = "MyAgent.dll";
int basePort = 4000;
int totalInstances = 100;
List<Process> runningAgents = new List<Process>();

Console.WriteLine("Preparing to start agent instances...");
for (int i = 0; i < totalInstances; i++)
{
    int port = basePort + i;
    Process agentProc = new Process();
    agentProc.StartInfo.WorkingDirectory = workingDir;
    agentProc.StartInfo.FileName = "dotnet";
    agentProc.StartInfo.ArgumentList.Add(dllPath);
    // 参数拆分传入,不要拼接
    agentProc.StartInfo.ArgumentList.Add("--urls");
    agentProc.StartInfo.ArgumentList.Add($"http://0.0.0.0:{port}");
    agentProc.StartInfo.UseShellExecute = false;
    agentProc.StartInfo.CreateNoWindow = true;
    
    agentProc.Start();
    runningAgents.Add(agentProc);
    Console.WriteLine($"Agent started | Port: {port} | PID: {agentProc.Id}");
}

Console.WriteLine($"All {totalInstances} agents are running. Press any key to stop all instances.");
Console.ReadKey();

// 批量停止所有实例
foreach (var proc in runningAgents)
{
    if (!proc.HasExited)
    {
        proc.Kill();
        proc.Dispose();
    }
}
补充注意事项
  • 子进程启动配置中UseShellExecute建议设置为false,跳过系统shell中转直接创建dotnet进程,参数传递更稳定,不会出现命令转义异常
  • 如果用StartInfo.Arguments属性传参而非ArgumentList,需要给监听地址加英文双引号包裹,格式为$"{dllPath} --urls \"http://0.0.0.0:{port}\"",避免特殊字符导致解析失败
  • 批量启动前可增加端口占用检测逻辑,提前跳过已被占用的端口,减少启动崩溃问题

内容的提问来源于stack exchange,提问作者Dave Anthony

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:27:33