Setting up SignalR and Nancy in Visual Studio 2015

A few of the side projects I’m working on at the moment are making use of SignalR for real-time communication between the browser and server, they are also using Nancy (a low ceremony web framework).

It took a few different blog posts and reading the Nancy documentation to figure out how to go from an empty ASP.Net project to having Nancy and SignalR playing nicely, so I’ve written this blog post outlining the process – as it turns out the process itself is pretty simple.

  1. Create a ASP.Net project
    1-new-project
  2. Select the Empty template
    2-empty-template
  3. Install the required Nancy NuGet packages:
    • Install-Package Nancy
    • Install-Package Nancy.Owin
  4. Install SignalR by adding a new SignalR Hub class3-add-signalr-hub
    public class HelloHub : Hub
    {
        public void Echo(string str)
        {
            Clients.Others.echo(str);
        }
    }
    
  5. Add a Startup class:
    namespace MyWebApp
    {
        using Owin;
    
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app
                    .MapSignalR()
                    .UseNancy();
            }
        }
    }
    
  6. Add a new Module
    public class IndexModule : NancyModule
    {
        public IndexModule()
        {
            Get["/"] = _ =>
            {
                return View["Index"];
            };
        }
    }
    
  7. Add the Index.html view
    <!DOCTYPE html>
    <html>
    <head>
        <title>MyWebApp</title>
    </head>
    <body>
    
    <div>
        </div>
    
        <script src="~/Scripts/jquery-1.10.2.js"></script>
        <script src="~/Scripts/jquery.signalR-2.1.2.js"></script>
        <script src="/signalr/hubs"></script>
        <script type="text/javascript">
            var myHub = $.connection.helloHub;
    
            myHub.client.echo = function (text) {
                console.info(text);
            };
    
            $.connection.hub.start();
        </script>
    </body>
    </html>
    
  8. Start debugging with Chrome and open two windows
  9. Open Chrome Developer tools (F12) in both windows, then in one type
    myHub.server.echo("test123");
    
  10. You should see the message appear in developer tools in the other window
    4-cross-window-messaging
Advertisements

One thought on “Setting up SignalR and Nancy in Visual Studio 2015

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s