【问题标题】:ApiExplorer for WebAPI controllers in external assemblyApiExplorer 用于外部程序集中的 WebAPI 控制器
【发布时间】:2015-09-08 16:05:44
【问题描述】:

我的 WebApi 控制器位于程序集中(自托管 OWIN 应用程序或 ASP MVC 应用程序)。 是否可以从另一个应用程序(动态加载带有 WebApi 控制器的程序集)中使用 ApiExplorer 来生成 Web API 文档?

【问题讨论】:

  • 您可以使用 Swagger:github.com/domaindrivendev/Swashbuckle
  • @Fals,谢谢。我需要用我的自定义结构生成一个 word 文档。在这种情况下,Swagger 可以帮助我吗?
  • 是的,已经有一个这样的问题stackoverflow.com/questions/30217910/…
  • @Fals,谢谢。但无论如何,它并没有解决我的任务。我必须在我的 WebApi 应用程序中安装额外的包。我希望能够使用我自己的应用程序来探索任何 WebApi 应用程序,以使用 reflexion 和 ApiExplorer 生成文档。也许,这是不可能的。
  • 这是可能的,但你会重新发明井,因为它已经做了你想做的事。有时第三方库是最好的选择。

标签: c# asp.net-web-api asp.net-mvc-apiexplorer


【解决方案1】:

ApiExplorer 使用 GlobalConfiguration 来确定可用的 ApiController。当您指定外部程序集时,您通常通过替换 WebApi 正在使用的 IAssemblyResolver 来执行此操作。这可以像这样在 Application_Start 中完成:

  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 的实现:

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:

public HelpController(HttpConfiguration config)
    {
        GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new AssemblyResolver());

        Configuration = config;
    }

可能有一种更清洁的方法可以做到这一点,这样您就不会破坏 DRY - 但还没有找到它。当我找到它时会更新这个帖子。

【讨论】:

  • 我添加了一个我如何实现 AssemblyResolver 的示例。您使用的是什么版本的 WebApi?
猜你喜欢
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多