Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.NET Web API:如何Host定义在独立程序集中的Controller

ASP.NET Web API:如何Host定义在独立程序集中的Controller2015-01-31通过《ASP.NET Web API的Controller是如何被创建的?》的介绍我们知道默认ASP.NET Web API在Self Host寄宿模式下用于解析程序集的AssembliesResolver是一个DefaultAssembliesResolver对象,它只会提供当前应用程序域已经加载的程序集。如果我们将HttpController定义在非寄宿程序所在的程序集中(实际上在采用Self Host寄宿模式下,我们基本上都会选择在独立的项目定义HttpController类型),即使我们将它们部属在宿主程序运行的目录中,宿主程序启动的时候也不会主动去加载这些程序集。由于当前应用程序域中并不曾加载这些程序集,HttpController类型解析将会失败,HttpController的激活自然就无法实现。[本文已经同步到《How ASP.NET Web API Works?》]

我们可以通过一个简单的实例来证实这个问题。我们在一个解决方案中定义了如右图所示的4个项目,其中Foo、Bar和Baz为类库项目,相应的HttpController类型就定义在这3个项目之中。Hosting是一个作为宿主的控制台程序,它具有对上述3个项目的引用。我们分别在项目Foo、Bar和Baz中定义了三个继承自ApiController的HttpController类型FooController、BarController和BazController。如下面的代码片断所示,我们在这3个HttpController类型中定义了唯一的Action方法Get并让它返回当前HttpController类型的AssemblyQualifiedName。

1: public class FooController : ApiController

2: {

3:     public string Get()

4:     {

5:         return this.GetType().AssemblyQualifiedName;

6:     }

7: }

8:  

9: public class BarController : ApiController

10: {

11:     public string Get()

12:     {

13:         return this.GetType().AssemblyQualifiedName;

14:     }

15: }

16:  

17: public class BarController : ApiController

18: {

19:     public string Get()

20:     {

21:         return this.GetType().AssemblyQualifiedName;

22:     }

23: }

我们在作为宿主的Hosting程序中利用如下的代码以Self Host模式实现了针对Web API的寄宿。我们针对基地址“http://127.0.0.1:3721”创建了一个HttpSelfHostServer,在开启之前我们注册了一个URL模板为“api/{controller}/{id}”的路由。

1: class Program

2: {

3:     static void Main(string[] args)

4:     {

5:         Uri baseAddress = new Uri("http://127.0.0.1:3721");

6:         using (HttpSelfHostServer httpServer = new HttpSelfHostServer(new HttpSelfHostConfiguration(baseAddress)))

7:         {

8:             httpServer.Configuration.Routes.MapHttpRoute(

9:                 name             : "DefaultApi",

10:                 routeTemplate    : "api/{controller}/{id}",

11:                 defaults         : new { id = RouteParameter.Optional });

12:  

13:             httpServer.OpenAsync().Wait();

14:             Console.Read();

15:         }

16:     }

17: }