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

.NET Core+SPA场景下WebSocket控制器端点无法执行求助

.NET Core WebSocket 连接异常排查

我创建了一个.NET Core控制器,使用Postman访问https://localhost:44447/api/callsynchronisation/ws的Get方法可正常执行(已通过构造函数和Get方法断点验证),代码如下:

public class CallSynchronisationController : ApiControllerBase
{
    private IWebSocketHandler handler;
    public CallSynchronisationController(IWebSocketHandler handler)
    {
        this.handler = handler;
    }

    [HttpGet("ws")]
    public async Task Get()
    {
        if (HttpContext.WebSockets.IsWebSocketRequest)
        {
            using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
            await handler.Handle(Guid.NewGuid(), webSocket);
        }
        else
        {
            HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
        }
    }
}

我在Startup.cs中添加了app.UseWebSockets()且该代码已正常执行,配置代码如下:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddApplicationServices();
builder.Services.AddInfrastructureServices(builder.Configuration);

builder.Services.AddWebUIServices();

var app = builder.Build();

app.UseWebSockets();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseMigrationsEndPoint();

    // Initialise and seed database
    using (var scope = app.Services.CreateScope())
    {
        var initialiser = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitialiser>();
        await initialiser.InitialiseAsync();
        await initialiser.SeedAsync();
    }
}
else
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios
    app.UseHsts();
}

app.UseHealthChecks("/health");
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseSwaggerUi3(settings =>
{
    settings.Path = "/api";
    settings.DocumentPath = "/api/specification.json";
});

app.UseRouting();

AddWebUIServices方法会调用services.AddControllersWithViews。我在Angular中配置的WebSocket地址为wss://localhost:44447/api/callsynchronisation/ws,但尝试发送消息时连接一直处于连接状态;Chrome中发起的ws请求始终未收到服务器响应,虽能看到正确的upgrade: websocket请求头,但控制器构造函数并未执行(此前的HTTPS Get请求则可触发构造函数)。请问哪里操作有误?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:20:47