使用OWIN身份验证使SignalR和CORS难以使用ASP.NET Web API v2。
似乎我可以使用CORS和SignalR或Web API,但不能同时使用它们。我正在通过代码配置CORS,因为尝试通过web.config添加标头对我来说不起作用。以下是Startup.cs的配置方法
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
HttpConfiguration httpConfig = new HttpConfiguration();
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
ConfigureWebApi(httpConfig);
app.UseWebApi(httpConfig);
}
使用上述配置 Web Api可以正常工作。我能够从客户端验证和调用API方法。但是,当客户端尝试访问SignalR脚本时,我收到错误。请注意第二条错误消息中的CORS错误No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
。
http://localhost:49834/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22loginhub%22%7D%5D&_=1461093918311 Failed to load resource: the server responded with a status of 404 (Not Found)
XMLHttpRequest cannot load http://localhost:49834/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22myhub%22%7D%5D&_=1461093918311. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.
这令人困惑...... 为什么CORS配置还不包括位于http://localhost:8080/signalr/
的SignalR脚本的路径?
所以在搜索了SO和Google搜索一段时间之后,我遇到了专门针对SignalR的SO post。建议的答案在下面添加了Configuration
方法。在SignalR工作之后!
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
// ****** Start added code ******
//Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true;
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
// ****** End added code *******
HttpConfiguration httpConfig = new HttpConfiguration();
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
ConfigureWebApi(httpConfig);
app.UseWebApi(httpConfig);
}
为什么第二部分需要配置?以便SignalR工作?不应该app.UseCors(CorsOptions.AllowAll);
有效吗?