寄宿于WindowsService的WebAPI

步骤:

1、创建WindowsService工程。

2、点击Manage NuGet Packages,查询Microsoft Asp.NET Web API Self Host,点击Install。

3、编辑service.cs文件如下:

 1 public partial class Service1 : ServiceBase
 2     {
 3         private HttpSelfHostServer _server;
 4         private readonly HttpSelfHostConfiguration _config;
 5         public const string ServiceAddress = "http://localhost:1345";
 6         public Service1()
 7         {
 8             InitializeComponent();
 9 
10             _config = new HttpSelfHostConfiguration(ServiceAddress);
11             _config.Routes.MapHttpRoute("DefaultApi",
12                 "api/{controller}/{id}",
13                 new { id = RouteParameter.Optional });
14         }
15 
16         protected override void OnStart(string[] args)
17         {
18             _server = new HttpSelfHostServer(_config);
19             _server.OpenAsync();
20         }
21 
22         protected override void OnStop()
23         {
24             _server.CloseAsync().Wait();
25             _server.Dispose();
26         }
27     }
28     public class ApiServiceController : ApiController
29     {
30         [HttpGet]
31         public string Get()
32         {
33             return "Hello from windows service!";
34         }
35     }

4、打开 Service1.cs 的视图设计器,在视图设计器中任意位置右键,选择”添加安装程序“,这时项目跟目下将出现一��?ProjectInstaller.cs 的组(如果是第一次添加”安装程序“的��,双击 ProjectInstaller.cs 打开 ProjectInstaller  的视图设计器,找到 serviceInstaller1 组件,选中后按 F4 键,设置组件属性��,Description=“测试服��?” DisplayName=“Service1”  ServiceName=“Service1”;//这个值必须和 WindowsService1.InitService() 方法下设置的 base.ServiceName 属性一至��, StartType 为服务运行类型,根据你的需要设置即可。(Manual:手动启动,AutoMatic 为自动启动),找到ceProcessInstaller1 组件,选中后按 F4 键,设置组件属性,Account=“LocalSystem”; //设置为其他的属性在开启服务时,会提示输入用户名和密码,这样就完成了一个服务的所有准备,下面就是安装和测试工作。
5、打开生成目录,如果生成成功会有一WindowsService1.exe 文件 ,在生成目录根目录下新加两bat(批处理文件),用于安装和卸载服,新建一个文本文件,打开文件加入以下两行命令   C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe WindowsService1.exe   pause   保存后关闭文本文件,之后将其重命名为“安装服.bat”文件,注意要修改后缀名为 .bat!,  再新建一个文本文件,打开文件加入以下两行命令   C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u WindowsService1.exe   pause   保存后关闭文本文件,之后将其重命名为“卸载服bat”文件,注意要修改后缀名为 .bat! 6.4 “安装服.bat”文件,安装windows 服务。安装成功后需要手动开启服务,因为我们刚设serviceInstaller1.StartType=Manual  打开windows 服务管理器,找到名为 Service1 的服务,右键属性。点击启动。

6.编译时安装卸载:

build events:Pre-build enent command line

net stop xxx exit /b 0

post-build event command line:

%systemroot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u $(TargetPath)
%systemroot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe $(TargetPath)

原文地址:https://www.cnblogs.com/super86/p/2936365.html