Why does ~/signalr/hubs return 404 ?

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

When working with SignalR hubs probably your first experience will be HTTP Error File not found (snapshot from Fiddler).

image

This happen when java script reference tries to download dynamically created hub.js file which helps you to easily deal with hub proxies. This is something similar to WCF dynamically created proxies in a case of AJAX. SignalR is very easy to use. However somehow I never started the project without running in this issue. :)

First of all you have to make sure that this file is generated at all. To generate this file you have to append following line in Application_Start.

protected void Application_Start()
{
    RouteTable.Routes.MapHubs();
}

This instructs SignalR runtime to prepare this file. However, exactly on this place there are few things you have to be aware of. If you are working ASP.NET MVC and Co. the Application_Start might look like:

      protected void Application_Start(){

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);        

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);          

            RouteConfig.RegisterRoutes(RouteTable.Routes);

 

            BundleConfig.RegisterBundles(BundleTable.Bundles);

 

            RouteTable.Routes.MapHubs();      // Here is HUB initialization    
        }

If you start this the client you will be surprised, but HUB file will not be found. This is because the hub must be initialized before registration of routes.
Following code shows the right registration order.

protected void Application_Start(){

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);        

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);   

            RouteTable.Routes.MapHubs();  // Here is HUB initialization           

            RouteConfig.RegisterRoutes(RouteTable.Routes);  // HUB initialization must be before route initialization!!!

            BundleConfig.RegisterBundles(BundleTable.Bundles);           
        }

 

Start now the client and be happy.

image

Note that the same issue can be caused be invalid script reference. Following snippets show how to create valid reference:


ASP.NET MVC 4:

      <script src="~/signalr/hubs"></script>

ASP.NET MVC 3 :

    <script src="@Url.Content("~/signalr/hubs")"></script>

ASP.NET page:

    <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>


Posted Mar 08 2013, 11:44 PM by Damir Dobric
Filed under: ,
developers.de is a .Net Community Blog powered by daenet GmbH.