7

I wanted to try out this example of a self-hosted webservice (originally written in WCF WebApi), but using the new ASP.NET WebAPI (which is the descendant of WCF WebApi).

using System;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.ApplicationServer.Http;

namespace SampleApi {
    class Program {
        static void Main(string[] args) {
            var host = new HttpServiceHost(typeof (ApiService), "http://localhost:9000");
            host.Open();
            Console.WriteLine("Browse to http://localhost:9000");
            Console.Read();
        }
    }

    [ServiceContract]
    public class ApiService {    
        [WebGet(UriTemplate = "")]
        public HttpResponseMessage GetHome() {
            return new HttpResponseMessage() {
                Content = new StringContent("Welcome Home", Encoding.UTF8, "text/plain")
            };    
        }
    }    
}

However, either I haven't NuGotten the right package, or HttpServiceHost is AWOL. (I chose the 'self hosting' variant).

What am I missing?

Benjol
  • 63,995
  • 54
  • 186
  • 268
  • [This](http://code.msdn.microsoft.com/ASPNET-Web-API-Self-Host-30abca12/view/Reviews) has helped me to get something working, but it doesn't look like a strict equivalent. – Benjol Mar 09 '12 at 10:00

1 Answers1

10

Please refer to this article for self-hosting:

Self-Host a Web API (C#)

The complete rewritten code for your example would be as follows:

class Program {

    static void Main(string[] args) {

        var config = new HttpSelfHostConfiguration("http://localhost:9000");

        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}", 
            new { id = RouteParameter.Optional }
        );

        using (HttpSelfHostServer server = new HttpSelfHostServer(config)) {

            server.OpenAsync().Wait();

            Console.WriteLine("Browse to http://localhost:9000/api/service");
            Console.WriteLine("Press Enter to quit.");

            Console.ReadLine();
        }

    }
}

public class ServiceController : ApiController {    

    public HttpResponseMessage GetHome() {

        return new HttpResponseMessage() {

            Content = new StringContent("Welcome Home", Encoding.UTF8, "text/plain")
        };    
    }
}

Hope this helps.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
tugberk
  • 57,477
  • 67
  • 243
  • 335