2012-03-09 1 views
7

Volevo provare l'esempio this di un servizio Web ospitato autonomamente (originariamente scritto in WCF WebApi), ma utilizzando la nuova Web API ASP.NET (che è il discendente di WCF WebApi).Qual è l'equivalente di HttpServiceHost in Web App di ASP.NET?

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") 
      };  
     } 
    }  
} 

Tuttavia, o non ho NuGotten il pacchetto giusto, o HttpServiceHost è assente ingiustificato. (Ho scelto la variante "self hosting").

Cosa mi manca?

+0

[This] (http://code.msdn.microsoft.com/ASPNET-Web-API-Self-Host-30abca12/view/Reviews) mi ha aiutato a far funzionare qualcosa, ma non sembra un equivalente rigoroso. – Benjol

risposta

10

Si prega di fare riferimento a questo articolo per self-hosting:

Self-Host a Web API (C#)

Il codice riscritto completo per il vostro esempio potrebbe essere il seguente:

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") 
     };  
    } 
} 

Spero che questo aiuti.