1. 程式人生 > WINDOWS開發 >Topshelf 搭建輕量級 Windows 服務 + Webapi

Topshelf 搭建輕量級 Windows 服務 + Webapi

建立控制檯專案

static void Main(string[] args)
        {
            var rc = HostFactory.Run(x =>
            {
                x.Service<AppServices>(s =>
                {
                    s.ConstructUsing(name => new AppServices());
                    s.WhenStarted(service => service.Start());
                    s.WhenStopped(service 
=> service.Stop()); s.OwinEndpoint(api => { api.Port = 9000; api.ConfigureHttp(httpConfiguration => { httpConfiguration.Routes.MapHttpRoute("DefaultApiWithId
","api/{controller}/{action}/{id}",new { action = RouteParameter.Optional,id = RouteParameter.Optional }); }); api.ConfigureAppBuilder(appBuilder => appBuilder.Use<CorsMiddleware>(CorsOptions.AllowAll)); }); }); x.RunAsLocalSystem();
//x.UseLog4Net("log4net.config"); x.SetDescription("DNC對接介面"); x.SetDisplayName("DNC對接介面"); x.SetServiceName("DNC.WebApi"); x.StartAutomaticallyDelayed(); }); log4net.Config.XmlConfigurator.Configure(); var exitCode = (int)Convert.ChangeType(rc,rc.GetTypeCode()); Environment.ExitCode = exitCode; }

新增xxxApiController類

public class DncController : ApiController
{
    [HttpPost]
    public string Send([FromBody]DownFileInputDto input)
    {
        return "hi";
    }
}

安裝服務:

以管理員身份執行cmd,執行 DNC-MES-Interface.exe install 命令安裝介面,執行 net start DNC.WebApi 命令啟用服務,介面執行在9000埠