标题总结了我的问题。我在服务的try-catch
方法和服务中的OnStart
方法周围有Main
个块,并且不会抛出任何异常。服务启动并立即停止,并显示以下消息:
本地计算机上的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);
}
}
WebApiService.cs:
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;
}
}
WebApiService.Designer.cs
partial class WebApiService
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Foo";
}
#endregion
}
的Program.cs:
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;
}
}
LogController.cs:
[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.Designer.cs,因为服务从InitializeComponent返回时会关闭。
修改2 :我已将其追溯到WebApp.Start<Startup>(baseUrl)
中的WebApiService.cs
。抛出 TargetInvocationException ,并将 HttpListenerException 作为内部异常。 HttpListenerException上的消息是“访问被拒绝。”
System.Reflection.TargetInvocationException occurred
HResult=0x80131604
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter.Create(IAppBuilder builder)
at Microsoft.Owin.Hosting.Engine.HostingEngine.StartServer(StartContext context)
at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider services, StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](String url)
at Foo.Logging.WebApi.WebApiService.OnStart(String[] args) in C:\Dev\Foo\Foo.WebApi\WebApiService.cs:line 45
Inner Exception 1:
HttpListenerException: Access is denied
我已经研究过可能的原因,它可能是URL或ACL。我将网址更改为http://+:{this.config.WebApiHttpPort}
,但无济于事。然后,我创建了一个ACL,如下所示:
netsh http add urlacl http://+:8089/ user=Everyone
错误仍然存在。