问题
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