最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - connect to signalr hub - Stack Overflow

programmeradmin3浏览0评论

I have created a simple SignalR hub inside a console application:

class Program
{
    static void Main(string[] args) 
    {    
        using (WebApp.Start<Startup>("http://localhost:1968"))
        {
            Console.WriteLine("Server running!");        
            Console.ReadLine();    
        } 
    } 
}

public static class UserHandler
{
    public static HashSet<string> ConnectedIds = new HashSet<string>();
}

[HubName("echo")]
public class EchoHub : Hub 
{ 
    public void Say(string message) 
    { 
        Trace.WriteLine("hub: "+message);
        Clients.All.AddMessage(message);
    }

    public override Task OnConnected()
    {
        UserHandler.ConnectedIds.Add(Context.ConnectionId);
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        UserHandler.ConnectedIds.Remove(Context.ConnectionId);
        return base.OnDisconnected();
    }
}

class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
        app.MapSignalR();
    } 
} 

When I try to connect this from a Silverlight App, it succeeds:

static Microsoft.AspNet.SignalR.Client.HubConnection signalR { get; set; }
public static Microsoft.AspNet.SignalR.Client.IHubProxy signalRhub { get; set; }

public static void StartSignalR()
{
    var url = "http://localhost:1968";
    signalR = new Microsoft.AspNet.SignalR.Client.HubConnection(url);
    signalR.Received += signalR_Received;
    signalRhub = signalR.CreateHubProxy("echo");
    signalR.Start().Wait();
    signalRhub.Invoke("Say", "hub invoked");
}

My next step is to connect the SignalR hub from jquery:

<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery.signalR-2.1.0.js"></script>
<script>
    $(function ()
    {
        var connection = $.hubConnection("http://localhost:1968");
        connection.start()
            .done(function () {
                console.log('connected');
                connection.send("success?");
            })
            .fail(function (a) {
                console.log('not connected'+a);
            });
    });
</script>

When I try to run this script, it gives the error:

"XMLHttpRequest cannot load localhost:1968/signalr/negotiate?clientProtocol=1.4&_=1404978593482. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>http://localhost:55282</code> is therefore not allowed access."

Why can I connect to the hub from my Silverlight page (hosted in localhost:3926)
and fails it when I run the jquery script (hosted in localhost:55282)?

What can I do to get a working connection between my jQuery and SignalR hub?

I have created a simple SignalR hub inside a console application:

class Program
{
    static void Main(string[] args) 
    {    
        using (WebApp.Start<Startup>("http://localhost:1968"))
        {
            Console.WriteLine("Server running!");        
            Console.ReadLine();    
        } 
    } 
}

public static class UserHandler
{
    public static HashSet<string> ConnectedIds = new HashSet<string>();
}

[HubName("echo")]
public class EchoHub : Hub 
{ 
    public void Say(string message) 
    { 
        Trace.WriteLine("hub: "+message);
        Clients.All.AddMessage(message);
    }

    public override Task OnConnected()
    {
        UserHandler.ConnectedIds.Add(Context.ConnectionId);
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        UserHandler.ConnectedIds.Remove(Context.ConnectionId);
        return base.OnDisconnected();
    }
}

class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
        app.MapSignalR();
    } 
} 

When I try to connect this from a Silverlight App, it succeeds:

static Microsoft.AspNet.SignalR.Client.HubConnection signalR { get; set; }
public static Microsoft.AspNet.SignalR.Client.IHubProxy signalRhub { get; set; }

public static void StartSignalR()
{
    var url = "http://localhost:1968";
    signalR = new Microsoft.AspNet.SignalR.Client.HubConnection(url);
    signalR.Received += signalR_Received;
    signalRhub = signalR.CreateHubProxy("echo");
    signalR.Start().Wait();
    signalRhub.Invoke("Say", "hub invoked");
}

My next step is to connect the SignalR hub from jquery:

<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery.signalR-2.1.0.js"></script>
<script>
    $(function ()
    {
        var connection = $.hubConnection("http://localhost:1968");
        connection.start()
            .done(function () {
                console.log('connected');
                connection.send("success?");
            })
            .fail(function (a) {
                console.log('not connected'+a);
            });
    });
</script>

When I try to run this script, it gives the error:

"XMLHttpRequest cannot load localhost:1968/signalr/negotiate?clientProtocol=1.4&_=1404978593482. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>http://localhost:55282</code> is therefore not allowed access."

Why can I connect to the hub from my Silverlight page (hosted in localhost:3926)
and fails it when I run the jquery script (hosted in localhost:55282)?

What can I do to get a working connection between my jQuery and SignalR hub?

Share Improve this question asked Jul 10, 2014 at 8:21 henkhenk 4171 gold badge5 silver badges14 bronze badges 5
  • 1 My guess is that this is interpreted as a cross site request, since the js is hosted at a different port than the SignalR hub. Same Origin Policy is in effect. – schei1 Commented Jul 10, 2014 at 8:39
  • That is plausible, but why can the Silverlight, also hosted on a different port, connect succesfully? And if so, is it possible to setup the SignalR hub so that cross request are allowed? – henk Commented Jul 10, 2014 at 10:04
  • Using CORS. It is the browser who is the offender. In the silverlight implementation you are using the .NET SignalR client I presume? – schei1 Commented Jul 10, 2014 at 10:38
  • You can use jsonp, but I would instead move SignalR to the webserver – Anders Commented Jul 10, 2014 at 10:53
  • Yes indeed, I use the .NET SignalR client. The solution provided by Vishal Ravlani seems to be working, thank you for your answers. – henk Commented Jul 10, 2014 at 10:58
Add a comment  | 

2 Answers 2

Reset to default 19

Change

$(function ()
    {
    var connection = $.hubConnection("http://localhost:1968");
    connection.start()
        .done(function () {
            console.log('connected');
            connection.send("success?");
        })
        .fail(function (a) {
            console.log('not connected'+a);
        });
});

to

$(function ()
{
var connection = $.hubConnection("http://localhost:1968");
var hub = connection.createHubProxy("echo");
hub.on("AddMessage", Method);
connection.start({ jsonp: true })
            .done(function () {
            console.log('connected');
            hub.say("success?");
        })
        .fail(function (a) {
            console.log('not connected'+a);
        });
});

function Method(messageFromHub)
{
alert(messageFromHub);
}

and

class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
        app.MapSignalR();
    } 
} 

to

class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
        app.MapSignalR(new HubConfiguration() { EnableJSONP = true });} 
} 

It should do.

app.MapSignalR(new HubConfiguration() { EnableJSONP = true });} 

and

connection.start({ jsonp: true })

Will allow cross site request

RPC on Server in SignalR with createHubProxy():

Thanks to the answer from Vishal Ravlani

But for me

hub.say("success?");

doesn't work! (Does it work for you?)

I have to write:

hub.invoke('say','success?');

And SignalR has automatically detected CrossOrigin on Client.

On Server I have used:

app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);

                map.RunSignalR();
            });

which was described on: http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#crossdomain

发布评论

评论列表(0)

  1. 暂无评论