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

Xamarin macOS项目中启动WebHost报PlatformNotSupportedException如何解决

错误原因

报错是因为WebHost.Run()方法默认会绑定Console.CancelKeyPress事件实现Ctrl+C终止服务的逻辑,但Xamarin macOS GUI应用不存在控制台上下文,Xamarin.Mac运行时未实现该控制台事件,因此抛出平台不支持异常。
另外你现有代码中的UseUrls参数存在语法错误,https//*:8842缺少协议分隔冒号,正确应为https://*:8842。

解决方案
  • 替换WebHost.Run()调用,改用手动管理生命周期的Start()/RunAsync()方法,跳过默认的控制台事件绑定逻辑
  • 配合Xamarin macOS应用的生命周期(如窗口关闭、应用退出事件)手动停止WebHost释放资源

修正后的代码示例

WebHost初始化与启动

// 先修正UseUrls的语法错误,初始化WebHost
this.webHost = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("https://*:8842") // 补全协议冒号
    .UseStartup<TestStartup>()
    .Build();

// 不要调用Run(),改用Start()异步启动,不会绑定控制台事件
await this.webHost.StartAsync();

// 也可以使用同步Start方法
// this.webHost.Start();

应用退出时停止WebHost(可放在窗口关闭事件、AppDelegate的WillTerminate方法中)

if (this.webHost != null)
{
    await this.webHost.StopAsync();
    this.webHost.Dispose();
}

如果需要等待WebHost运行结束,可以自行监听应用退出的CancellationToken:

// 示例:将应用退出的取消令牌传递给RunAsync
var cancellationToken = // 绑定你自己的应用退出取消令牌
await webHost.RunAsync(cancellationToken);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:15:04