SignalR, Filters and ServiceStack - StrathWeb

Strath

March 3rd, 2013

SignalR, Filters and ServiceStack

I recently blogged about a technique of integrating SignalR with ASP.NET Web API through the use of action filters.

A few people have asked, whether this approach (and SignalR now being part of Microsoft’s ASP.NET product group after all) works with other frameworks. And the answer is absolutely yes.

Let’s have a look at implementing this for ServiceStack.

Adding ServiceStack

You should probably have a look at the original article first, since the SignalR part of it will be identical. Let’s start today by adding ServiceStack through Nuget:

To enable ServiceStack endpoints, we also need to add SS handler to web.config, under the handlers section:

This will setup all requests to /service to go through the ServiceStack pipeline. Additionally, we need to exclude this route from MVC processing, by adding the following ignore directive:

The SignalR setup (hubs, JavaScript, HTML, routes) is the same as in the previous post.

Creating ServiceStack filters

The only difference from the Web API approach is that with service stack you get separate filter for pre-execution of the service method, and a separate one for post-execution.

Therefore, instead of implementing one attribute, like before, we will do it in two. Just to remind you (if you really didn’t read the last post) – in the request we will capture the body and flush down in real time to the “admin” interface together with a timestamp. The same will happen when the response gets sent down to the client; all of which combines into a neat real time logging mechanism

Request:

And response:

In both cases, the principles are almost identical as with Web API; the main difference is that we don’t need to tack on the async API to deal with reading the request body and so on, since ServiceStack will expose all that synchronously.

However, in ServiceStack the default request behavior is bufferless input stream, whereas in Web API it is buffered. Bufferless obviously means that once ServiceStack took ownership of the request and pulled out the DTO from it, the request stream is at the end and not available to be re-read (which is what we are trying to do in the request filter).

To remedy that, we cans witch ServiceStack’s mode of operation to buffered, by adding this to our AppHost:

Running it

Now suppose you have a simple ServiceStack host:

We could add our attributes to the service:

And if we navigate to the same log.html which we created in the last post for Web API, and start making requests, the log will start filling in real time.

This is pretty neat and shows you an easy way to do SignalR integration. On a side note, ServiceStack already has a pretty robust logging infrastructure, so this might not be the best use case, but hopefully it illustrates the concept.

Be Sociable, Share!