【发布时间】:2017-12-12 05:36:46
【问题描述】:
我有一个运行 SignalR 2.2.2 的 ASP.NET MVC 5 应用程序,此应用程序在 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 运行它时它工作正常
错误:协商请求期间出错。
通过将以下内容添加到Web.config 文件中的<system.webServer></system.webServer> 部分,在我的集线器应用上启用CORS。
<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);
}
什么可能导致此错误?还需要做什么才能从其他应用连接到我的集线器?
用于连接到我的集线器的代码如下,可在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.
【问题讨论】:
-
hubConfiguration.EnableCrossDomain = true;
-
EnableCrossDomain 不是 SignalR 2 上的选项
-
@MrgGek 需要
Microsoft.Owin.Cors需要 Asp.Net-Core 而不是 Asp.Net-MVC-5 的包 -
不需要asp.net core
标签: c# asp.net-mvc asp.net-mvc-5 signalr signalr-hub