ASP.NET WebAPI中HttpServiceHost的等价物是什么?

时间:2012-03-09 07:58:44

标签: c# wcf-web-api asp.net-web-api

我想尝试this自托管Web服务(最初使用WCF WebApi编写)的示例,但使用新的ASP.NET WebAPI(它是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")
            };    
        }
    }    
}

但是,要么我没有NuGotten正确的包,要么HttpServiceHost是AWOL。 (我选择了'自托管'变体)。

我错过了什么?

1 个答案:

答案 0 :(得分:10)

请参阅此文章以获取自托管:

Self-Host a Web API (C#)

您的示例的完整重写代码如下:

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

希望这有帮助。