问题描述
我的WebApi控制器位于程序集(自托管的OWIN应用程序或ASP MVC应用程序)中.是否可以通过其他应用程序(通过WebApi控制器动态加载程序集)使用ApiExplorer生成Web API文档?
My WebApi controllers are located in an assembly (self-hosted OWIN application or ASP MVC application).Is it possible to use ApiExplorer form another application (that loads an assembly with WebApi controllers dynamically) to generate Web API documentation?
推荐答案
ApiExplorer使用GlobalConfiguration来确定可用的ApiController.指定外部程序集时,通常可以通过替换WebApi使用的IAssemblyResolver来执行此操作.可以这样在Application_Start中完成:
ApiExplorer uses the GlobalConfiguration to determine the available ApiControllers. When you specify an external assembly you typically do this by replacing the IAssemblyResolver that WebApi is using. This can be done in Application_Start like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents();
GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new AssemblyResolver());
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
这是AssemblyResolver的实现:
Here's the implementation of AssemblyResolver:
public class AssemblyResolver : System.Web.Http.Dispatcher.DefaultAssembliesResolver
{
public override ICollection<Assembly> GetAssemblies()
{
ICollection<Assembly> baseAssemblies = base.GetAssemblies();
List<Assembly> assemblies = new List<Assembly>(baseAssemblies);
var externalAssembly = typeof(MyApp.External).Assembly;
assemblies.Add(externalAssembly);
return baseAssemblies;
}
}
可能有人认为这足以让ApiExplorer拿起它,但事实并非如此.当ApiExplorer启动时,GlobalConfiguration会传递给HelpController.如果仔细查看GlobalConfiguration实例,您会发现在Application_Start中受影响的更改不存在.因此,要让ApiExplorer选择您的外部类,您可以像这样更新IAssemblyResolver:
One might think that this is enough for ApiExplorer to pick it up but it is not. When ApiExplorer starts the GlobalConfiguration is passed to the HelpController. If you look carefully at the instance of GlobalConfiguration you will see that the changes you affected in your Application_Start are not there. So, to get ApiExplorer to pick up your external class you can just update the IAssemblyResolver like this:
public HelpController(HttpConfiguration config)
{
GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new AssemblyResolver());
Configuration = config;
}
可能有一种更清洁的方法来执行此操作,这样您就不会破坏DRY-但尚未找到它.找到后将更新此帖子.
There is probably a cleaner way to do this so you don't break DRY - but have not found it yet. Will update this post when I find it.
这篇关于外部程序集中用于WebAPI控制器的ApiExplorer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!