脱离IIS的WebAPI

创建控制台工程

创建纯净版webApi程序(前面的博客有提到)

webAPI中引入nuget包 a) Microsoft.AspNet.WebApi.OwinSelfHost   b)Microsoft.AspNet.WebApi.WebHost

webAPI中新增启动类

 1 using Microsoft.Owin;
 2 using Owin;
 3 using System.Web.Http;
 4 [assembly: OwinStartup(typeof(WebApi.Startup))]
 5 namespace WebApi
 6 {
 7     public class Startup
 8     {
 9         public void Configuration(IAppBuilder app)
10         {
11             HttpConfiguration config = new HttpConfiguration();
12             config.Routes.MapHttpRoute(
13                 name: "DefaultApi",
14                 routeTemplate: "api/{controller}/{id}",
15                 defaults: new { id = RouteParameter.Optional }
16             );
17             app.UseWebApi(config);
18         }
19 
20     }
21 }

webAPI中添加控制器(前面的文章中有提到)

 1 using System.Web.Http;
 2 namespace WebApi.Controllers
 3 {
 4     public class WebAppController : ApiController
 5     {
 6         [HttpGet]
 7         public string Hello()
 8         {
 9             return "hello world";
10         }
11 
12     }
13 }

控制台程序中引入nuget包 a)Microsoft.AspNet.WebApi.OwinSelfHost  b)Topshelf

控制台程序引用webapi项目

控制台程序 添加类 StartJob

 1 using Microsoft.Owin.Hosting;
 2 using System;
 3 using WebApi;
 4 
 5 namespace WebApiService
 6 {
 7     class StartJob
 8     {
 9         IDisposable dis = null;
10         public void Start()
11         {
12             dis = WebApp.Start<Startup>(url: "http://localhost:9088/");
13 
14         }
15         public void Stop()
16         {
17             dis.Dispose();
18             dis = null;
19         }
20 
21     }
22 }

控制台程序,在Main函数创建windows服务并启动

 1 using Topshelf;
 2 namespace WebApiService
 3 {
 4     class Program
 5     {
 6         static void Main(string[] args)
 7         {
 8 
 9             HostFactory.Run(x =>
10             {
11                 x.Service<StartJob>(s =>
12                 {
13                     s.ConstructUsing(name => new StartJob());//创建对象实例
14                     s.WhenStarted(t => t.Start());//服务启动时候,启动Time
15                     s.WhenStopped(t => t.Stop());//服务关闭时候,关闭Time
16                 });
17 
18 
19                 x.RunAsLocalSystem();
20                 x.SetDescription("The Windows Service For WebApi");//这个是服务的描述
21                 x.SetDisplayName("WebApiService");//这个是服务的显示名称
22                 x.SetServiceName("WebApiService");//这个是服务的名称
23             });
24         }
25     }
26 }

启动程序

a)编译程序WebApiService.exe,cmd并进入WebApiService.exe程序所在的目录

b)安装程序

c

c)启动程序

4)使用浏览器访问创建的hello方法

浏览器地址栏中输入:http://localhost:9088/api/webapp/hello

如果要卸载服务,请使用

原文地址:https://www.cnblogs.com/ErricShih/p/10337110.html