2012-03-09 45 views
7

Tôi muốn thử this ví dụ về dịch vụ web tự lưu trữ (ban đầu được viết bằng WCF WebApi), nhưng sử dụng ASP.NET WebAPI mới (là hậu duệ của WCF WebApi).Tương đương với HttpServiceHost trong ASP.NET WebAPI là gì?

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

Tuy nhiên, tôi chưa NuGotten gói đúng hoặc HttpServiceHost là AWOL. (Tôi đã chọn biến thể 'tự lưu trữ').

Tôi đang thiếu gì?

+0

[Điều này] (http://code.msdn.microsoft.com/ASPNET-Web-API-Self-Host-30abca12/view/Reviews) đã giúp tôi làm việc gì đó nhưng không giống một tương đương nghiêm ngặt. – Benjol

Trả lời

10

Vui lòng tham khảo bài viết này để tự lưu trữ:

Self-Host a Web API (C#)

Mã viết lại hoàn chỉnh cho ví dụ của bạn sẽ như sau:

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.

Các vấn đề liên quan