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

如何从.NET 4.8 WebForms应用连接到ASP.NET Core7 MVC的SignalR Hub

WebForms连接ASP.NET Core SignalR Hub协商错误解决指南

问题场景

现有.NET 4.8 ASP.NET WebForms应用与ASP.NET Core 7 MVC应用,需通过WebForms的JavaScript连接MVC端的SignalR Hub,实现WebForms登录时通知Hub、MVC向WebForms广播消息的双向通信。但WebForms客户端连接时触发「Error during negotiation request」错误,客户端代码如下:

$(document).ready(function () {
    var connection = $.hubConnection();

    connection.url = "https://localhost:44312/chatHub";
    var myChatHubProxy = connection.createHubProxy('chatHub');

    connection.start()
        .done(function () {
            // Logic on connection start
        })
        .fail(function (err) {
            console.error(err);
        });

    // Additional code.
});

核心原因

WebForms中使用的是SignalR旧版jQuery客户端,而ASP.NET Core SignalR是完全重写的实现,两者通信协议不兼容,这是协商请求失败的核心原因。

解决步骤

1. 替换WebForms端的SignalR客户端库

弃用旧版jquery.signalR-x.x.x.js,改用ASP.NET Core SignalR官方JavaScript客户端:

  • 下载@microsoft/signalr的浏览器版脚本文件,放入WebForms项目的静态资源目录(如~/lib/signalr/)
  • 在WebForms页面中引用该脚本:
    <script src="~/lib/signalr/dist/browser/signalr.js"></script>
    

2. 重写客户端连接代码

旧版API($.hubConnection()、createHubProxy)不兼容Core SignalR,需按Core版语法重构:

$(document).ready(function () {
    // 构建Core SignalR连接实例
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("https://localhost:44312/chatHub")
        .withCredentials() // 跨域场景下需开启,用于传递Cookie(如登录状态)
        .build();

    // 监听Hub推送的消息(需与MVC端Hub的方法名对应)
    connection.on("ReceiveMessage", function (sender, content) {
        console.log(`${sender}: ${content}`);
        // 此处添加消息展示逻辑
    });

    // 启动连接
    connection.start()
        .then(function () {
            // 连接成功后执行逻辑(如登录时通知Hub)
            connection.invoke("SendLoginNotify", "WebForms用户已登录")
                .catch(err => console.error(err.toString()));
        })
        .catch(err => console.error(err.toString()));
});

3. 配置MVC端的CORS策略

由于WebForms与MVC是独立应用(存在跨域),需在ASP.NET Core的Program.cs中配置CORS允许WebForms域名访问:

var builder = WebApplication.CreateBuilder(args);

// 添加CORS服务
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowWebFormsOrigin", policy =>
    {
        // 替换为WebForms应用的实际域名(如https://localhost:44300)
        policy.WithOrigins("https://localhost:你的WebForms端口")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

// 注册SignalR服务
builder.Services.AddSignalR();

var app = builder.Build();

// 启用CORS(必须放在UseRouting之前)
app.UseCors("AllowWebFormsOrigin");

app.UseRouting();
app.UseAuthorization();

// 映射Hub路由
app.MapHub<ChatHub>("/chatHub");

app.Run();

4. 验证MVC端Hub配置

确保MVC端的Hub继承自Microsoft.AspNetCore.SignalR.Hub,方法名与客户端调用/监听的一致:

using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
    // 接收WebForms端的登录通知
    public async Task SendLoginNotify(string message)
    {
        // 向所有客户端广播消息
        await Clients.All.SendAsync("ReceiveMessage", "系统通知", message);
    }
}

额外排查方向

  • 直接访问https://localhost:44312/chatHub/negotiate,检查是否返回正常协商响应,排查CORS或服务器内部错误
  • 确认WebForms与MVC的HTTPS证书均被信任,避免SSL证书错误导致请求失败
  • 检查MVC端的SignalR路由是否与客户端配置的/chatHub完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:30:15