Issue with SignalR core and cross domain requests

余生颓废 提交于 2019-12-22 10:43:52

问题


We are using SignalR core with CORS cross domain requests. The client is unable to connect to server. 401 Unauthorized No Access-Control-Allow-Origin' header is present on the requested resource. Error: Failed to start the connection. Note we are using the most recent signalr core (alpha version for asp.net core 2.0).

Please note within the same client app, i'm able to access CORS Web API methods. It's isolated to SignalR hub/client.

We are using Windows authentication in IIS. Anonymous seems to be working.

Server startup.cs:

ConfigureServices() method

services.AddCors();
services.AddSignalR();

Configure method

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseSignalR(routes =>
            {
                routes.MapHub<TestHub>("test");
            });
app.UseMvc();

javascript client:

let connection = new signalR.HubConnection(CORS_WEB_API_URL + '/test');
    connection.on('send', data => {
        console.log(data);
    });
connection.start();

Please advise.


回答1:


I know this is an old post, however, the answer is that with SignalR you cannot use wildcards in the CORS allow origin.

Needs to be specific. For development I use this:

        services.AddCors(options => options.AddPolicy("CorsDev", builder =>
        {
            builder
            .AllowAnyMethod()
            .AllowAnyHeader()
            .WithOrigins(AppSettings.SPAHost, "http://localhost:8099")
            .AllowCredentials();
        }));

Then in Configure in startup.cs

app.UseCors("CorsDev");

Hope this helps someone.




回答2:


Just replace .AllowAnyOrigin() with .WithOrigins("*")

ConfigureServices:

services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
     builder
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithOrigins("*")
        .AllowCredentials();
}));

Configure

app.UseCors("CorsPolicy");

Tested with

<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.2" />


来源:https://stackoverflow.com/questions/48894774/issue-with-signalr-core-and-cross-domain-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!