Search code examples
asp.net-web-api2owinsignalr-hubself-hosting

Self-Host SignalR and Web Api in a single Console Application


In a single Console Application I must self-host both a SignalR Server and a Web Api.

I'm using this code

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
using Microsoft.Owin.Cors;
using System.Web.Http;
using System.Net.Http;

namespace SignalRSelfHost
{
    class Program
    {
        static void Main(string[] args)
        {

            string url = "http://localhost:8080";
            using (WebApp.Start(url))
            {
                Console.WriteLine("Server running on {0}", url);

                //////////


                // Create HttpCient and make a request to api/values 
                HttpClient client = new HttpClient();

                var response = client.GetAsync(url + "/api/values").Result;

                Console.WriteLine(response);
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                Console.ReadLine();


                //////////




                Console.ReadLine();
            }
        }
    }
    class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            ////////
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            app.UseWebApi(config);
            /////////

            app.MapSignalR();
        }
    }
    public class MyHub : Hub
    {
        public void Send(string name, string message)
        {
            Clients.All.addMessage(name, message);
        }
    }
}

and I've entered the following commands:

Install-Package Microsoft.AspNet.SignalR.SelfHost

Install-Package Microsoft.Owin.Cors

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Now the SignalR server works OK, but not the WebApi: it gives me "No HTTP resource was found that matches the request URI 'http://localhost:8080/api/values'". My controller class is the following:

namespace SignalRSelfHost
{
    class ValuesController : ApiController
    {
        // GET api/values 
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

Anyone can help me?


Solution

  • Set your ValuesController from private to public and it should work.