SignalR 的跨域支持

How to establish a cross-domain connection

Typically if the browser loads a page from http://contoso.com, the SignalR connection is in the same domain, athttp://contoso.com/signalr. If the page from http://contoso.com makes a connection to http://fabrikam.com/signalr, that is a cross-domain connection. For security reasons, cross-domain connections are disabled by default.

In SignalR 1.x, cross domain requests were controlled by a single EnableCrossDomain flag. This flag controlled both JSONP and CORS requests. For greater flexibility, all CORS support has been removed from the server component of SignalR (JavaScript clients still use CORS normally if it is detected that the browser supports it), and new OWIN middleware has been made available to support these scenarios.

If JSONP is required on the client (to support cross-domain requests in older browsers), it will need to be enabled explicitly by settingEnableJSONP on the HubConfiguration object to true, as shown below. JSONP is disabled by default, as it is less secure than CORS.

Adding Microsoft.Owin.Cors to your project: To install this library, run the following command in the Package Manager Console:

Install-Package Microsoft.Owin.Cors

This command will add the 2.1.0 version of the package to your project.

Calling UseCors

The following code snippet demonstrates how to implement cross-domain connections in SignalR 2.

Implementing cross-domain requests in SignalR 2

The following code demonstrates how to enable CORS or JSONP in a SignalR 2 project. This code sample uses Map and RunSignalR instead ofMapSignalR, so that the CORS middleware runs only for the SignalR requests that require CORS support (rather than for all traffic at the path specified in MapSignalR.) Map can also be used for any other middleware that needs to run for a specific URL prefix, rather than for the entire application.

using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Owin;
namespace MyWebApplication
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 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);
});
}
}
}
上一篇:关于JAVA Project.waitfor()死锁问题


下一篇:k-近邻算法(KNN)