问题
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,
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", "*");
回答1:
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;
}
回答2:
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.
来源:https://stackoverflow.com/questions/20487351/custom-headers-and-signalr-asp-net-mvc4-web-api