我有一个在Visual Studio中创建的可执行文件,我希望能将其创建为服务(这样就不需要使用控制台窗口运行它了)。我发布该项目并使用以下方法创建Windows服务:
sc create MY.SERVICE binpath= "C:\Program Files\Project\serviceProj\myService.exe
这项服务会如预期一样出现在Windows服务管理器中。但是,每当我尝试启动该服务时,它在大约2秒钟后失败,并给我以下错误提示:
Windows could not start the MY.SERVICE on Local Computer.
Error 1053: The service did not respond to the start or control request in a timely fashion.
我所做的事情:
在Visual Studio中将Debug更改为Release。
以管理员身份运行所有操作(创建服务、发布项目、启动服务等)。
我也曾在某个地方看到,增加服务管理器等待服务启动时间的长度可能会起作用。我添加了Windows注册表值来实现这一点,但不幸的是它没有起作用。
在命令提示符中启动服务通常只需要2-3秒钟就能启动并开始监听请求,因此我不确定发生了什么问题。
感激任何帮助。
以下是我的Startup.cs类:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Hosting.WindowsServices;
using System.Diagnostics;
using System.IO;
using Serilog;
using System.Linq;
namespace My.Service
{
public class Startup
{
public static void Main(string[] args)
{
var exePath = Process.GetCurrentProcess().MainModule.FileName;
var directoryPath = Path.GetDirectoryName(exePath);
if (Debugger.IsAttached || args.Contains("--debug"))
{
var host = new WebHostBuilder()
.CaptureStartupErrors(true)
.UseKestrel()
.UseUrls("http://localhost:5002")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
else
{
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://localhost:5002")
.UseContentRoot(directoryPath)
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.RunAsService();
}
}
public Startup(IHostingEnvironment env)
{
//Setup Logger
Log.Logger = new LoggerConfiguration()
.WriteTo.Trace()
.MinimumLevel.Debug()
.CreateLogger();
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
}
}
}