SignalR responses overwriting headers

2019-06-19 08:44发布

问题:

I've built a simple SignalR hub that lives within a WebAPI service, I've included all the required CORS attributes on both WebAPI and SignalR. My WebAPI endpoints are all working as expected but SignalR isn't.

I've tried all I can think of and all I can find online but nothing works, I already tried this answer, and this other to no solution.

My SignalR extension method looks like this

public static IAppBuilder UseSignalrNotificationService(this IAppBuilder app)
    {
        var config = new HubConfiguration();
        config.Resolver = new HubDependencyResolver();
        config.EnableDetailedErrors = true;
        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR(config);

        return app;
    }

And I even tried adding the response headers on all requests using the Web.config but I allways get the same error:

XMLHttpRequest cannot load https://MyApplicationServer/notifications/signalr/negotiate?clientProtocol=1.5&access_token=&connectionData=. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'MyOriginService' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

回答1:

After more research and fiddling with the server side of the problem, I ran into this answer and found the error to be with the client side of the request. according to this GitHub issue, the "withCredentials" parameter of the request is always set to 'true'. The solution was to call on the client the start method as follows:

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


回答2:

Are you changing the request somewhere with some kind of global interceptor? For some reason, the XMLHttpRequest starts with withCredentials:true and this is forbidden when the Access-Control-Allow-Origin is set to *.

What about setting the 'Access-Control-Allow-Origin' to 'http://MyApplicationServer'? It's safer than * and will remove your problem at source.