以Self Host的方式来寄宿Web API

Common类及实体定义、Web API的定义请参见我的上一篇文章:以Web Host的方式来寄宿Web API

一、以Self Host寄宿需要新建一个Console控制台项目(SelfHost)

这个项目也需要引用之前定义的WebApi项目或者把WebApi.dll放到此项目的执行Bin目录下,

另外,需要引用的DLLs如下:

  1. System.Web.Http.dll  (C:Program Files (x86)Microsoft ASP.NETASP.NET MVC 4AssembliesSystem.Web.Http.dll)
  2. System.Web.Http.WebHost.dll(C:Program Files (x86)Microsoft ASP.NETASP.NET MVC 4AssembliesSystem.Web.Http.WebHost.dll)
  3. System.Net.Http.dll(C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.6System.Net.Http.dll)

具体代码如下:

 1 using System;
 2 using System.Reflection;
 3 using System.Threading.Tasks;
 4 using System.Web.Http;
 5 using System.Web.Http.SelfHost;
 6 
 7 namespace SelfHost
 8 {
 9     internal static class Program
10     {
11         private static void Main(string[] args)
12         {
13             // 加载包含Web API的程序集
14             Assembly.Load("WebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
15 
16             // 采用BaseAddress来初始化HTTP服务的配置类
17             var configuration = new HttpSelfHostConfiguration("http://localhost/selfhost");
18 
19             // 生成直接侦听HTTP的Server实例 
20             using (var httpServer = new HttpSelfHostServer(configuration))
21             {
22                 // 注册路由
23                 httpServer.Configuration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
24                 var task = httpServer.OpenAsync();
25                 if (task.Status == TaskStatus.WaitingForActivation)
26                 {
27                     Console.WriteLine("Http Server started!");
28                 }
29                 Console.Read();
30             }
31         }
32     }
33 }

 WCF服务寄宿的时候我们必须指定寄宿服务的类型,但是对于ASP.NET Web API的寄宿来说,不论是Web Host还是Self Host我们都无须指定IHttpController的类型。也就是说,WCF服务寄宿是针对具体某个服务类型的,而ASP.NET Web API的寄宿则是批量的。ASP.NET Web API的批量寄宿源自它对HttpController类型的智能解析,它会从程序集列表中解析出所有的HttpController类型。对于WebHost来说,它会利用BuildManager来获得当前项目直接或者间接引用的程序集,但是对于Self Host来说,类型的解析在默认情况下只会针对加载到当前应用程序域中的程序集列表。

二、测试

把SelfHost项目设置为启动项目,Ctrl+F5执行程序;

原文地址:https://www.cnblogs.com/frankyou/p/4683496.html