Signalr - Override method for sending messages

2019-07-03 08:28发布

问题:

I have an implementation of the PersistentConnection class in Signalr. For our site, I need to be able to broadcast a message, and then have each connection determine whether that particular message is relevant for that specific user before sending it down the pipe to the browser.

Something like this:

public class MyConnection : PersistentConnection {

    private int _UserID;

    public override void OnSending(object message) {
        var msg = message as MyNotification;
        if(msg != null && !msg.CanRead(_UserID))
            return;
        base.OnSending(message);
    }

}

Is this possible?

Right now, we have a custom session state object. Upon connection, the id is added to the users session object. When we have a message to send out, we raise an event and each session determines whether to pass the message along to its associated client ids. I really want to decouple this from our session object.

回答1:

You can create a hub pipeline module to get this affect.

For instance you can do:

public class MyModule : HubPipelineModule
{
    protected override bool OnBeforeOutgoing(IHubOutgoingInvokerContext context)
    {
        return context.Connection.ShouldSend();
    }
}

Then in your Application_Start:

GlobalHost.HubPipeline.AddModule(new MyModule());

Of course you would need to add the ShouldSend method to the IConnection interface and the corresponding connection objects but this would give you your desired result.

For more info on the the hub pipeline modules see the Hub Pipeline section at http://weblogs.asp.net/davidfowler/archive/2012/11/11/microsoft-asp-net-signalr.aspx