【发布时间】:2017-10-31 10:26:09
【问题描述】:
我正在尝试实现here 中提到的 ASP.NET SignalR 应用程序。
我已经实现了here 中提到的客户端。对于客户端,我使用的是没有生成代理的代码。
客户端和服务器在同一域中时成功连接,但在托管跨域时无法通信。虽然上面文章中提到的跨域代码已经实现了。由于我的客户端和服务器托管在 Azure 中,Azure 中是否有需要启用跨域通信的设置,或者我还缺少其他什么?
这是我得到的错误:
请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许 Origin 访问。响应的 HTTP 状态代码为 500。
我的创业班是:
public void Configuration(IAppBuilder app)
{
//app.UseCors(CorsOptions.AllowAll);
// Any connection or hub wire up and configuration should go here
//app.MapSignalR();
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
而客户端代码是:`
$(function (){
var ChatServerUrl ="http://chatserverurl.net/home/";
var ChatUrl = ChatServerUrl + "signalr";
var connection = $.hubConnection(ChatUrl, { useDefaultPath: false });
connection.logging = true;
var chatHubProxy = connection.createHubProxy('chatHub');
chatHubProxy.on('addNewMessageToPage', function (name, message) {
console.log("AddNewMessageToPage Function!");
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
});
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
//connection.start({ withCredentials : false }).done(function () {
connection.start({ withCredentials: true }).done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chatHubProxy.invoke('Send', $('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
console.log("SignalR Connected!");
});
});`
【问题讨论】:
-
你看到了吗:docs.microsoft.com/en-us/aspnet/signalr/overview/… - 本文包含关于跨域连接的部分。
-
是的,我已经实现了同样的
标签: asp.net model-view-controller signalr cross-domain