Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Headers and Signalr: Asp.Net MVC4 Web Api

I am using signalr (version 2.0.0) in my asp.net mvc4 webapi project,

Here to allow cross origin resource sharing, i use the following code in webconfig file

 <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <remove name="X-Powered-By" />
  </customHeaders>

Here is the client side signalr code for receiving data from server:

 $(function () {
    var nodePublishingHub = $.connection.nodePublishingHub;
    nodePublishingHub.client.NodePublished = onNewMessage;

    $.connection.hub.error(function (error) {
        $('#messages').append('<li>' + error + '</li>');
    });

    $.connection.hub.url = "http://localhost:5441/signalr";
    $.connection.hub.start({ transport: 'longPolling' })
});

I am using the following code to enable CORS with signalr,

 public void Configuration(IAppBuilder app)
    {
        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration
            {
                EnableJSONP = true
            };
            map.RunSignalR(hubConfiguration);
        });
    }

However error occurs,

XMLHttpRequest cannot load http://localhost:5441/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%…name%22%3A%22nodepublishinghub%22%7D%5D&clientProtocol=1.3&_=1386654835296. The 'Access-Control-Allow-Origin' header contains the invalid value 'null, *'. Origin 'null' is therefore not allowed access.

How can i solve this issue? Please help.

I tried the following,

  1. I added this code in golbal.asax but it only makes each method cros enaled, so i couldnt get images from server to process.

      HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    
like image 603
Erma Isabel Avatar asked Dec 10 '13 06:12

Erma Isabel


2 Answers

Do not modify signalr original source code. When will update your code will stop working.

Prefer this instead:

$.connection.hub.start({ withCredentials: false }).done(function () {
  //...
}

start({ withCredentials: false }) instead of the tipical start() will do the job. You can verify here (GitHub issue tracker) the official support.

like image 163
Vincenzo Avatar answered Oct 16 '22 11:10

Vincenzo


Erma

This should do the trick

go to your jquery.signalr 2.0.0.js file and change withCredentials = true to false

if (typeof (config.withCredentials) === "undefined") { config.withCredentials = false; }

like image 22
Tinku Chacko Avatar answered Oct 16 '22 11:10

Tinku Chacko