天天看点

WebApi脱离IIS

题记:建个脱离iis的web项目,查到webapi是可以寄宿到其他应用程序的,控制台及windows服务等,特翻了很多文档,多次测试无效果,也走了不少弯路,特记录一下

1、本地使用环境,vs2012 + .net4.0,通过Nuget程序包 增加webapi2的时候,一直失败苦恼中(后发现切换到.net4.5时正常),经查官方文档 4.0下使用webapi1正常了,成功之后开始了项目的测试

WebApi脱离IIS

---------------------------------------------寄宿于控制台程序--------------------------------------------------

2、新建控制台程序 (测试用例参考微软官方帮助文档 https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/self-host-a-web-api)

3、新建类,命名Product

public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
           

4、新建类,命名 ProductsController  控制器

public class ProductsController : ApiController
    {
        Product[] products = new Product[]  
        {  
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },  
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },  
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }  
        };

        [HttpPost]
        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }

        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            return products.Where(p => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
           

5、补充 控制台的Main函数

var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
           

6、生成应用程序,管理员启动即可

7、使用postman工具 调用服务 http://localhost:8080/api/product 

WebApi脱离IIS

8、宿主为控制台的webapi搭建完毕

---------------------------------------------寄宿于windows服务改造--------------------------------------------------

1、新建 windows服务 项目,默认Service1

2、建实体类及控制类,如上

3、定义及完善Service1服务

private HttpSelfHostServer _server;
        private readonly HttpSelfHostConfiguration _config;
        public const string ServiceAddress = "http://localhost:8080";
        public Service1()
        {
            InitializeComponent();
             _config = new HttpSelfHostConfiguration(ServiceAddress);
             _config.Routes.MapHttpRoute("DefaultApi",
                 "api/{controller}/{id}",
                 new { id = RouteParameter.Optional });
        }

        protected override void OnStart(string[] args)
        {
            _server = new HttpSelfHostServer(_config);
            _server.OpenAsync();
        }

        protected override void OnStop()
        {
            _server.CloseAsync().Wait();
            _server.Dispose();
        }
           

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、打开目录,设置安装和卸载的bat命令,文本保存改为bat后缀

--安装
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe WindowsService1.exe   
pause 

--卸载
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u WindowsService1.exe
pause
           

6、安装成功后需要手动开启服务,因为我们刚设serviceInstaller1.StartType=Manual  打开windows 服务管理器,找到名为 Service1 的服务,右键属性。点击启动。

7、使用工具调用,成功

后面抽些时间,了解下路由的跳转