将 SignalR 与 Web API 和 JavaScript Web App 一起使用,并支持 CORS

目标: 使用 SignalR 在 Web API 和基于 TypeScript / JavaScript 的 Web App 之间进行通知,其中 Web API 和 Web App 托管在不同的域中。

在 Web API 上启用 SignalR 和 CORS: 创建标准 Web API 项目,并安装以下 NuGet 包:

  • Microsoft.Owin.Cors
  • Microsoft.AspNet.WebApi.Cors
  • Microsoft.AspNet.WebApi.Owin
  • Microsoft.AspNet.SignalR.Core

之后,你可以摆脱 Global.asax 并添加一个 OWIN Startup 类。

using System.Web.Http;
using System.Web.Http.Cors;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebAPI.Startup), "Configuration")]
namespace WebAPI
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
        
            var httpConfig = new HttpConfiguration();
            
            //change this configuration as you want.
            var cors = new EnableCorsAttribute("http://localhost:9000", "*", "*"); 
            httpConfig.EnableCors(cors);

            SignalRConfig.Register(app, cors);

            WebApiConfig.Register(httpConfig);

            app.UseWebApi(httpConfig);
        }
    }
}

创建 SignalRConfig 类如下:

using System.Linq;
using System.Threading.Tasks;
using System.Web.Cors;
using System.Web.Http.Cors;
using Microsoft.Owin.Cors;
using Owin;

namespace WebAPI
{
    public static class SignalRConfig
    {
        public static void Register(IAppBuilder app, EnableCorsAttribute cors)
        {

            app.Map("/signalr", map =>
            {
                var corsOption = new CorsOptions
                {
                    PolicyProvider = new CorsPolicyProvider
                    {
                        PolicyResolver = context =>
                        {
                            var policy = new CorsPolicy { AllowAnyHeader = true, AllowAnyMethod = true, SupportsCredentials = true };

                            // Only allow CORS requests from the trusted domains.
                            cors.Origins.ToList().ForEach(o => policy.Origins.Add(o));

                            return Task.FromResult(policy);
                        }
                    }
                };
                map.UseCors(corsOption).RunSignalR();
            });
        }
    }
}

到目前为止,我们刚刚在服务器端启用了带有 CORS 的 SignalR。现在让我们看看如何从服务器端发布事件。为此我们需要一个 Hub

public class NotificationHub:Hub
{
    //this can be in Web API or in any other class library that is referred from Web API.
}

现在终于实际广播变化的一些代码:

public class SuperHeroController : ApiController
{
    [HttpGet]
    public string RevealAlterEgo(string id)
    {
        var alterEgo = $"The alter ego of {id} is not known.";
        var superHero = _superHeroes.SingleOrDefault(sh => sh.Name.Equals(id));
        if (superHero != null)
        {
            alterEgo = superHero.AlterEgo;
            
            /*This is how you broadcast the change. 
             *For simplicity, in this example, the broadcast is done from a Controller, 
             *but, this can be done from any other associated class library having access to NotificationHub.
             */
            var notificationHubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
            if (notificationHubContext != null)
            {
                var changeData = new { changeType = "Critical", whatHappened = $"Alter ego of {id} is revealed." };

                //somethingChanged is an arbitrary method name.
                //however, same method name is also needs to be used in client.
                notificationHubContext.Clients.All.somethingChanged(changeData);
            }
        }
        return alterEgo;
    }
}

因此,到目前为止,我们已经准备好了服务器端。对于客户端,我们需要 jQuerysignalr 包。你可以使用 jspm 安装。如果需要,安装两者的类型。

我们不会使用默认生成的 JavaScript 代理。我们宁愿创建一个非常简单的类来处理 SignalR 通信。

/**
 * This is created based on this gist: https://gist.github.com/donald-slagle/bf0673b3c188f3a2559c.
 * As we are crreating our own SignalR proxy, 
 * we don't need to get the auto generated proxy using `signalr/hubs` link.
 */
export class SignalRClient {

    public connection = undefined;
    private running: boolean = false;

    public getOrCreateHub(hubName: string) {
        hubName = hubName.toLowerCase();
        if (!this.connection) {
            this.connection = jQuery.hubConnection("https://localhost:44378");
        }

        if (!this.connection.proxies[hubName]) {
            this.connection.createHubProxy(hubName);
        }

        return this.connection.proxies[hubName];
    }

    public registerCallback(hubName: string, methodName: string, callback: (...msg: any[]) => void,
        startIfNotStarted: boolean = true) {

        var hubProxy = this.getOrCreateHub(hubName);
        hubProxy.on(methodName, callback);

        //Note: Unlike C# clients, for JavaScript clients, 
        //      at least one callback needs to be registered, 
        //      prior to start the connection.
        if (!this.running && startIfNotStarted)
            this.start();
    }

    start() {
        const self = this;
        if (!self.running) {
            self.connection.start()
                .done(function () {
                    console.log('Now connected, connection Id=' + self.connection.id);
                    self.running = true;
                })
                .fail(function () {
                    console.log('Could not connect');
                });
        }
    }
}

最后使用此类来收听更改广播,如下所示:

/**
 * Though the example contains Aurelia codes, 
 * the main part of SignalR communication is without any Aurelia dependency.
 */
import {autoinject, bindable} from "aurelia-framework";
import {SignalRClient} from "./SignalRClient";

@autoinject
export class SomeClass{
    
    //Instantiate SignalRClient.
    constructor(private signalRClient: SignalRClient) {
    }

    attached() {
        //To register callback you can use lambda expression...
        this.signalRClient.registerCallback("notificationHub", "somethingChanged", (data) => {
            console.log("Notified in VM via signalr.", data);
        });
        
        //... or function name.
        this.signalRClient.registerCallback("notificationHub", "somethingChanged", this.somethingChanged);
    }

    somethingChanged(data) {
        console.log("Notified in VM, somethingChanged, via signalr.", data);
    }
}