How to create a SignalR server project

C#/XAML for HTML5 edited this page Aug 17, 2017 · 2 revisions

How to create a SignalR server project:

  1. Create a new project of type "ASP.NET Web Application"

  2. Add the package "Microsoft.AspNet.SignalR" (to do so, right-click the project in the Solution Explorer, click "Manage NuGet Packages...", search for SignalR, then select "Microsoft.AspNet.SignalR", and click Install)

  3. Create a new class named "Startup.cs" and put the following code:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SilverlightSignalRTest.Web.Startup))]
namespace SilverlightSignalRTest.Web
{
  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      app.MapSignalR();
    }
  }
}
  1. Create a new class named for example "ChatHub", and put the following code (this is a sample code for implementing the SignalR Hub of a chat application):
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace SilverlightSignalRTest.Web
{
  [HubName("ChatHub")]
  public class ChatHub : Hub
  {
    public void SendMessage(string name, string message)
    {
      Clients.All.received(name, message);
    }
  }
}
  1. You need to add cross-domain support to your server project, so that any client application can connect to it. This can be done by implementing "CORS". To do so, add the "Global.asax" file (to do so, right-click the project in the Project Explorer, click "Add", click "Global Application Class", and name it "Global"), and use the following code:
  protected void Application_BeginRequest(object sender, EventArgs e)
  {
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
      //These headers are handling the "pre-flight" OPTIONS call sent by the browser
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, SOAPAction");
      HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
      HttpContext.Current.Response.End();
    }
  }
  1. Take note of the server address. To do so, open the Properties of the server project, go to the "Web" tab, and read the line "Project Url". It should read something like: "http://localhost:56581/" You will need this information to let the client application connect to the server. To do so, in your client application, you should pass the server address to the HubConnection class constructor:
   var connection = new HubConnection("http://localhost:56581/");
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.