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端口

posted @ 2020-05-20 11:16  も不秃不秃  阅读(906)  评论(2编辑  收藏  举报