我有一个正在运行的 ASP.NET MVC 5 应用 SignalR 2.2.2此应用程序正在 hub.domain.com
上运行.在另一个基于 Asp.Net MVC-5 的应用程序(即 localhost:15371
)上,我想与中心进行交互。
在我的 localhost:15371
应用程序,我添加了以下代码
<script>
var myHubHost = 'http://hub.domain.com/';
</script>
<script src="http://hub.domain.com/Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="http://hub.domain.com/signalr/hubs"></script>
<script src="http://hub.domain.com/signalr/custom_code.js"></script>
但是,当我尝试连接到 app.domain.com
上的集线器时出现以下错误但是当我直接从 hub.domain.com
运行它时它工作正常
Error: Error during negotiation request.
启用CORS
在我的中心应用程序上,将以下内容添加到我的 <system.webServer></system.webServer>
Web.config
部分文件。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
我也尝试启用 JSONP
以及我的集线器上的详细错误,如下所示
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = true;
hubConfiguration.EnableJSONP = true;
app.MapSignalR(hubConfiguration);
}
是什么导致了这个错误?从另一个应用程序连接到我的中心还需要做什么?
用于连接到 my hub 的代码如下,可在 custom_code.js
中找到文件。
$(document).ready(function () {
// Reference the auto-generated proxy for the hub.
var app = $.connection.myHubName;
// The getApiUrl() method return http://hub.domain.com/signalr
// as the myHubHost variable is set to http://hub.domain.com/
$.connection.hub.url = getApiUrl('signalr');
$.connection.hub.error(function (error) {
console.log(error)
});
// Create a function that the hub can call back get the new events
app.client.updatePanel = function (message) {
// Do stuff
}
// Start the connection.
$.connection.hub.start();
// This allows me to set a variable to control the base-url host when including this file on a different app.
function getApiUrl(uri)
{
var link = "/";
if (typeof window.myHubHost !== typeof someUndefinedVariableName) {
link = window.myHubHost;
}
return link + uri;
}
});
已更新
我像这样启用了日志记录
$.connection.hub.logging = true;
我还安装了Microsoft.Owin.Cors
根据 documentation 启用 cors 的软件包.这是我当前的配置
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true
};
map.RunSignalR(hubConfiguration);
});
这是我在控制台中获得的日志。如您所见,协商失败。
SignalR: Auto detected cross domain url.
SignalR: Client subscribed to hub 'myHubName'.
SignalR: Negotiating with 'http://hub.domain.com/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D'.
SignalR error: Error: Error during negotiation request.
SignalR: Stopping connection.
最佳答案
我终于找到了我的问题。
我的布局中有导致问题的 html 基本标记。
我删除了
我的问题解决了!
关于c# - 如何从不同的主机连接到我的 SignalR 集线器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757638/