3

我想使用 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 服务中托管时如何实现此目的?

4

3 回答 3

3

It's actually pretty simple. In a nutshell you need to instantiate HttpSelfHostServer and HttpSelfHostConfiguration and then call server.OpenAsync().

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

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

For an example on how to do this using Windows service project template and/or Topshelf library see my blog post: http://www.piotrwalat.net/hosting-web-api-in-windows-service/

于 2012-06-12T09:01:43.823 回答
2

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

如果您仍然有问题,请在 Twitter 上联系我。

于 2011-10-20T01:57:51.440 回答
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();
}

请参阅博客文章。

于 2011-10-20T08:51:13.680 回答