Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding some filters to hub methods (like AcctionFilters in MVC)

Is there anyway to define and add method filters for hub functions (like ActionFilters in mvc) I mean something like this :

public class MyHub : Hub 
{

    [Log]
    public string RegisterUser(UserModel model){
        ...
    }
}

where I can do some control inside the LogAttribute implementation.

like image 923
Mahmoud Moravej Avatar asked Jul 23 '14 11:07

Mahmoud Moravej


1 Answers

You should be able to achieve similar functionality to action filters in ASP.NET MVC by using SignalR's Hub pipeline:

public class LoggingPipelineModule : HubPipelineModule 
{ 
    protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context) 
    {
        Debug.WriteLine("Invoking '{0}.{1}({2})'.",
            context.MethodDescriptor.Hub.Name,
            context.MethodDescriptor.Name,
            string.Join(", ", context.Args));

        return base.OnBeforeIncoming(context); 
    }

    protected override object OnAfterIncoming(object result, IHubIncomingInvokerContext context)
    {
        Debug.WriteLine("Finished Invoking '{0}.{1}'. Returned '{2}'.",
            context.MethodDescriptor.Hub.Name,
            context.MethodDescriptor.Name,
            result);

        return base.OnAfterIncoming(result, context); 
    }
}

If you only want to log for methods with a custom attribute attached, you can check for your custom attribute before logging:

protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context) 
{
    if (context.MethodDescriptor.Attributes.OfType<MyAttribute>().Any())
    {
        // Log here.
    }

    return base.OnBeforeIncoming(context); 
}

You can register your module before your call to MapSignalR:

public void Configuration(IAppBuilder app) 
{ 
    GlobalHost.HubPipeline.AddModule(new LoggingPipelineModule()); 
    app.MapSignalR();
}
like image 164
halter73 Avatar answered Nov 15 '22 16:11

halter73