C# 通过Owin承载Web API 2的Windows服务启动并立即停止,不会引发异常

C# 通过Owin承载Web API 2的Windows服务启动并立即停止,不会引发异常,c#,asp.net-web-api2,owin,C#,Asp.net Web Api2,Owin,标题概括了我的问题。我在服务的OnStart方法和服务中的Main方法周围有try-catch块,并且从未抛出异常。服务启动并立即停止,并显示以下消息: 本地计算机上的Foo服务已启动,然后停止。一些 如果服务未被其他服务使用,则服务将自动停止 或程序 在测试服务器上可以观察到相同的行为,因此它不依赖于机器。我已验证配置文件是否存在并包含适当的设置 我看不出有什么明显的原因会发生这种情况。有人能看一下这个并解释一下吗?我咨询过其他类似的问题,但没有一个能说明这项服务 Startup.cs: pu

标题概括了我的问题。我在服务的
OnStart
方法和服务中的
Main
方法周围有
try-catch
块,并且从未抛出异常。服务启动并立即停止,并显示以下消息:

本地计算机上的Foo服务已启动,然后停止。一些 如果服务未被其他服务使用,则服务将自动停止 或程序

在测试服务器上可以观察到相同的行为,因此它不依赖于机器。我已验证配置文件是否存在并包含适当的设置

我看不出有什么明显的原因会发生这种情况。有人能看一下这个并解释一下吗?我咨询过其他类似的问题,但没有一个能说明这项服务

Startup.cs:

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();
        config.MapHttpAttributeRoutes();
        appBuilder.UseWebApi(config);
    }
}
public partial class WebApiService : ServiceBase
{
    private readonly IConfig config;
    private IDisposable webApp;

    public WebApiService()
    {
        try
        {
            InitializeComponent();
            this.config = UnityBootstrapper.Initialize().Resolve<IConfig>();
        }
        catch (Exception e)
        {
            new ApplicationEventLog(new Config()).WriteError(e);
        }
    }

    protected override void OnStart(string[] args)
    {
        try
        {
            var baseUrl = $"http://*:{this.config.WebApiHttpPort}";

            this.webApp = WebApp.Start<Startup>(baseUrl);
        }
        catch (Exception e)
        {
            new ApplicationEventLog(this.config).WriteError(e);
        }
    }

    protected override void OnStop()
    {
        this.webApp?.Dispose();
        this.webApp = null;
    }

    protected override void OnShutdown()
    {
        this.webApp?.Dispose();
        this.webApp = null;
    }
}
public static class Program
{
    public static bool IsConsoleApp = false;
    public static bool LogRequests = false;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    public static void Main(params string[] args)
    {
        try
        {
            if (args.Length > 0 && args.Any(a => a.ToLower().In("l", "-l", "/l")))
            {
                LogRequests = true;
            }

            if (args.Length > 0
                && args[0].ToLower().In("c", "-c", "/c"))
            {
                RunAsApp();
            }
            else
            {
                RunAsService();
            }
        }
        catch (Exception e)
        {
            new ApplicationEventLog(new Config()).WriteError(e);
        }
    }

    private static void RunAsService()
    {
        Program.IsConsoleApp = false;

        var servicesToRun = new ServiceBase[]
                                      {
                                          new WebApiService()
                                      };
        ServiceBase.Run(servicesToRun);
    }

    private static void RunAsApp()
    {
        Program.IsConsoleApp = true;

        var config = UnityBootstrapper.Initialize().Resolve<IConfig>();
        var url = $"http://*:{config.WebApiHttpPort}";

        Console.WriteLine($@"Running. Hosted at: {url}");
        Console.WriteLine(@"Press ENTER to exit.");

        using (WebApp.Start<Startup>(url))
        {
            while (Console.ReadKey().Key != ConsoleKey.Enter)
            {
                Thread.Sleep(0);
            }
        }

        Program.IsConsoleApp = false;
    }
}
[RoutePrefix("api/log")]
public class LogController : ApiController
{
    private readonly ILogger logger;
    private readonly IContextFactory contextFactory;
    private readonly IConfig config;

    public LogController() : base()
    {
        var container = UnityBootstrapper.Initialize();

        this.logger = container.Resolve<ILogger>();
        this.config = container.Resolve<IConfig>();
        this.contextFactory = container.Resolve<IContextFactory>();
    }

    [HttpGet]
    [Route("Status")]
    public string Status()
    {
    }

    [HttpPost]
    [Route("Message")]
    public string Write([FromBody] LogMessage logMessage)
    {
        // Elided for ... reasons
    }

    [HttpPost]
    [Route("Performance")]
    public string Write([FromBody] PerformanceMessage performanceMessage)
    {
        // Elided for ... reasons
    }
}
WebApiService.cs:

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();
        config.MapHttpAttributeRoutes();
        appBuilder.UseWebApi(config);
    }
}
public partial class WebApiService : ServiceBase
{
    private readonly IConfig config;
    private IDisposable webApp;

    public WebApiService()
    {
        try
        {
            InitializeComponent();
            this.config = UnityBootstrapper.Initialize().Resolve<IConfig>();
        }
        catch (Exception e)
        {
            new ApplicationEventLog(new Config()).WriteError(e);
        }
    }

    protected override void OnStart(string[] args)
    {
        try
        {
            var baseUrl = $"http://*:{this.config.WebApiHttpPort}";

            this.webApp = WebApp.Start<Startup>(baseUrl);
        }
        catch (Exception e)
        {
            new ApplicationEventLog(this.config).WriteError(e);
        }
    }

    protected override void OnStop()
    {
        this.webApp?.Dispose();
        this.webApp = null;
    }

    protected override void OnShutdown()
    {
        this.webApp?.Dispose();
        this.webApp = null;
    }
}
public static class Program
{
    public static bool IsConsoleApp = false;
    public static bool LogRequests = false;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    public static void Main(params string[] args)
    {
        try
        {
            if (args.Length > 0 && args.Any(a => a.ToLower().In("l", "-l", "/l")))
            {
                LogRequests = true;
            }

            if (args.Length > 0
                && args[0].ToLower().In("c", "-c", "/c"))
            {
                RunAsApp();
            }
            else
            {
                RunAsService();
            }
        }
        catch (Exception e)
        {
            new ApplicationEventLog(new Config()).WriteError(e);
        }
    }

    private static void RunAsService()
    {
        Program.IsConsoleApp = false;

        var servicesToRun = new ServiceBase[]
                                      {
                                          new WebApiService()
                                      };
        ServiceBase.Run(servicesToRun);
    }

    private static void RunAsApp()
    {
        Program.IsConsoleApp = true;

        var config = UnityBootstrapper.Initialize().Resolve<IConfig>();
        var url = $"http://*:{config.WebApiHttpPort}";

        Console.WriteLine($@"Running. Hosted at: {url}");
        Console.WriteLine(@"Press ENTER to exit.");

        using (WebApp.Start<Startup>(url))
        {
            while (Console.ReadKey().Key != ConsoleKey.Enter)
            {
                Thread.Sleep(0);
            }
        }

        Program.IsConsoleApp = false;
    }
}
[RoutePrefix("api/log")]
public class LogController : ApiController
{
    private readonly ILogger logger;
    private readonly IContextFactory contextFactory;
    private readonly IConfig config;

    public LogController() : base()
    {
        var container = UnityBootstrapper.Initialize();

        this.logger = container.Resolve<ILogger>();
        this.config = container.Resolve<IConfig>();
        this.contextFactory = container.Resolve<IContextFactory>();
    }

    [HttpGet]
    [Route("Status")]
    public string Status()
    {
    }

    [HttpPost]
    [Route("Message")]
    public string Write([FromBody] LogMessage logMessage)
    {
        // Elided for ... reasons
    }

    [HttpPost]
    [Route("Performance")]
    public string Write([FromBody] PerformanceMessage performanceMessage)
    {
        // Elided for ... reasons
    }
}
我已经研究了可能的原因,可能是URL或ACL。我将URL更改为
http://+:{this.config.WebApiHttpPort}
,但没有成功。然后,我创建了一个ACL,如下所示:

netsh http add urlacl http://+:8089/ user=Everyone

错误仍然发生。

调试服务时会发生什么?由于服务立即停止,我无法将Visual Studio的调试器附加到该服务。我可以运行它作为一个控制台应用程序,tho,它工作得很好。让我看看将Debugger.Launch()添加到主例程时会发生什么。windows应用程序事件日志中没有其他内容?服务在哪个帐户下运行?请参阅@PeterBons,它在为应用程序保留的特殊服务帐户下运行。它在整个网络中具有管理权限。@Camiloterevento我向OnStart添加了一个额外时间请求(值5分钟!)。这使我可以将VS调试器附加到它。奇怪的是,当WebApiService中的InitializeComponent完成时,它只是停止运行,没有任何警告。它永远无法实现初始化Unity的调用。令人费解。