在ASP.NET WebAPI中,HttpServiceHost相当于哪个对象?

7

我想尝试自托管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")
            };    
        }
    }    
}

然而,我要么没有得到正确的软件包,要么HttpServiceHost不知所踪。(我选择了“自托管”变体。)
我错过了什么吗?

这个链接帮助我实现了一些功能,但它似乎并不是严格等价的。 - Benjol
1个回答

10
请参考此文章进行自托管:

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

希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接