在Windows服务中使用OWIN托管WebAPI

Nar*_*ana 46 asp.net-web-api owin

我使用OWIN(在Windows服务中)自我托管Web API.据我所知,这足以让HTTP请求进入Windows服务.我可以在http://localhost/users本地(来自同一台机器)点击WebAPI URL(),但不能从其他机器点击.我正在使用端口80,IIS已停止.当IIS运行时,其他网站(在IIS中,在端口80上托管)可以正常工作.

//在Windows服务中:

public partial class Service1 : ServiceBase
{
    ...
    ...

    protected override void OnStart(string[] args)
    {
        Console.WriteLine("Starting service...");
        string baseAddress = "http://localhost:80/";
        WebApp.Start<Startup>(baseAddress);  //This is OWIN stuff.
    }
    ...
    ...
}

public class Startup
{
    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host.
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        appBuilder.UseWebApi(config);
    }
}
Run Code Online (Sandbox Code Playgroud)

我是否需要做更多的工作才能让其他机器正常工作?(我感觉传入的http请求没有被转发到Windows服务,只能转发到IIS.当你点击本地时,可能它不会通过侦听http请求的操作系统模块.只是一个猜测.)

Kir*_*lla 54

您的计算机的防火墙可能会阻止传入的请求.你可以这样做:

您可以运行wf.msc命令以打开具有高级安全性的Windows防火墙,并为TCP端口80添加新的入站规则.

(您应该注意到一些入站规则开始World Wide Web Services....这些是针对IIS的.我不确定启用这些规则是否足以让您的Windows服务接收请求...您可以尝试查看这是否有效之前建议,你可以创建一个新的入站规则..)

更新:
根据您的评论,可能是因为您的Url注册,您无法点击该服务.以下是使用HttpListener注册多个URL的一些示例.

StartOptions options = new StartOptions();
options.Urls.Add("http://localhost:9095");
options.Urls.Add("http://127.0.0.1:9095");
options.Urls.Add(string.Format("http://{0}:9095", Environment.MachineName));

using (WebApp.Start<Program>(options))
{
Run Code Online (Sandbox Code Playgroud)

:您可以通过以下链接了解更多关于URL登录
http://technet.microsoft.com/en-us/library/bb630429.aspx
http://technet.microsoft.com/en-us/library/bb677364. ASPX

  • 你可以简单地在`http://*:9095 /`启动它,这样它就会响应每个可用的地址. (55认同)

小智 18

有两件事会阻止你在Owin服务中使用与"localhost"不同的东西:

  1. 该应用程序需要以管理员身份运行才能打开具有不同主机名的端口作为"localhost".您可以通过使用管理员权限运行应用程序或使用以下命令为给定端口添加例外来解决此问题:netsh http add urlacl url=http://*:9000/ user=<your user>
  2. Windows防火墙可能会阻止来自其他计算机的流量.在我的情况下,防火墙没有阻止本地流量(我可以到达http://localhost:9000http://127.0.0.1:9000http://192.168.1.193:9000- 这是我在同一台计算机上的本地IP地址,但需要向防火墙添加端口例外以允许从另一台计算机获取此服务)


小智 6

我面临着类似的问题.以下解决方案适合我.

StartOptions options = new StartOptions();
options.Urls.Add("http://localhost:9095");
options.Urls.Add("http://127.0.0.1:9095");
options.Urls.Add(string.Format("http://{0}:9095", Environment.MachineName));

using (WebApp.Start<Program>(options))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)