如何在Windows服务中托管Web API

时间:2011-10-20 01:34:00

标签: wcf-web-api

我有几个我想使用WCF Web API公开的资源。我已经使用Web主机调查了Web API,但我们的服务都在生产中作为Windows服务运行,所以现在是时候让我把测试放在一边并验证一切都能按我们的需要运行。我在这里看作示例应用程序:http://webapicontrib.codeplex.com/SourceControl/changeset/view/2d771a4d6f6f#Samples%2fSelfHosted%2fserver%2fProgram.cs但这不适用于当前版本(预览5),因为无法从我们的代码访问HttpConfigurableServiceHost类。

Web API最吸引人的方面之一是使用MapServiceRoute和新的WebApiConfiguration进行简单启动。但是,我没有看到为服务定义基本URL和端口的方法。显然,在IIS中托管服务可以消除这种情况,因为我们在IIS中配置了这些信息。如何在Windows服务中托管?

3 个答案:

答案 0 :(得分:3)

实际上非常简单。简而言之,您需要实例化HttpSelfHostServer和HttpSelfHostConfiguration,然后调用server.OpenAsync()。

public void Start()
{
    _server.OpenAsync();
}

public void Stop()
{
    _server.CloseAsync().Wait();
    _server.Dispose();
}

有关如何使用Windows服务项目模板和/或Topshelf库执行此操作的示例,请参阅我的博客文章:http://www.piotrwalat.net/hosting-web-api-in-windows-service/

答案 1 :(得分:2)

最新版本只使用HttpServiceHost。 http://webapicontrib.codeplex.com/SourceControl/changeset/view/ddc499585751#Samples%2fSelfHosted%2fserver%2fProgram.cs

如果你继续遇到问题,请在Twitter上给我打电话。

答案 2 :(得分:1)

这是使用控制台应用程序的基本代码。 Windows服务使用相同的基本方法,除了使用start和stop方法来启动和停止服务而不需要阻止。

static void Main(string[] args)
{
    var host = new HttpServiceHost(typeof(PeopleService), "http://localhost:8080/people");

    host.Open();

    foreach (var ep in host.Description.Endpoints)
    {
        Console.WriteLine("Using {0} at {1}", ep.Binding.Name, ep.Address);
    }

    Console.ReadLine();

    host.Close();
}

请参阅this博文。

相关问题