asp.net-mvc - 具有基于命名空间的 ApiController 的自定义 ApiExplorer

标签 asp.net-mvc api documentation asp.net-apicontroller asp.net-mvc-apiexplorer

我正在尝试在我的后端系统中添加 API 文档。 默认的 ApiExplorer 和帮助页面工作得非常好,直到我向我的 Api Controller 引入版本为止。

为了添加版本,我在 Controllers 文件夹下创建了子文件夹:

  • v1
  • v2
  • v3

并且有基于版本的 Api Controller 。为了让我的 Api 可以被发现,我必须重写 DefaultHttpControllerSelector 以考虑任何客户端提供的命名空间并将它们映射到正确的 Controller :

这破坏了我的默认 ApiExplorer,并且以下属性返回零 api 描述

Configuration.Services.GetApiExplorer().ApiDescriptions

我如何定制现有的 ApiExplorer 并帮助他找到我的 Api Controller 而不是重写整个 ApiExplorer 实现。我真的需要展示在哪里可以找到我的 Api Controller 。

请指教。

最佳答案

我将向您展示一种方法来做到这一点。这段代码仅供学习。在这里我不谈论设计和最佳实践,所以请随意更改您想要的任何内容。

那么,您必须执行以下步骤:

1) 创建自定义 ApiExplorer:

public class MyApiExplorer: ApiExplorer
{
    private readonly string _version;

    public MyApiExplorer(string version) : base(GlobalConfiguration.Configuration)
    {
        _version = version != null ? version.ToUpperInvariant() : "V1";

        foreach(var apiDescription in ApiDescriptions)
        {
            apiDescription.RelativePath = apiDescription.RelativePath.Replace("{version}", _version);
        }

    }

    public override bool ShouldExploreController(string controllerVariableValue, HttpControllerDescriptor controllerDescriptor,
        IHttpRoute route)
    {
        return controllerDescriptor.ControllerType.FullName.Contains(_version);
    }

}

a) In the constructor _version will be converted to upperCase (just in case it will be passed as lowerCase) but if it is null then it will take V1 as default. Then change relative path to show specific version instead of {version}.

b) ShouldExploreController (in short words) decide if specific controller is taken to show in documentation. In this case we will only show controllers that its type full name contains choosed version.

2) 转到 HelpController 类并更改 Index 方法,如下所示:

public ActionResult Index(string version)
{
    //...

    Configuration.Services.Replace(typeof(IApiExplorer), new MyApiExplorer(version));

    return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}

We are replacing current ApiExplorer by our own in order to be returned when call to Configuration.Services.GetApiExplorer()

现在您可以使用 .../help?version=v1 或 .../help?version=v2 或 .../help?version=v3,您将获得特定的 api Controller 文档。

关于asp.net-mvc - 具有基于命名空间的 ApiController 的自定义 ApiExplorer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21690218/

相关文章:

r - R套件手册中的排除功能

asp.net-mvc - .mdf 文件无法在运行时附加 MVC4

java - In-App Review 调用 Log 但不发起对话

c# - 使用数据库优先方法时覆盖或替换默认构造函数

api - Jmeter - POST API 不工作

xml - 在 Angular 5 中使用 XML 数据发出 Post 请求

c# - 在 C# 中继承文档?

android - 是否有 Android Skia logcat 输出的文档?

c# - 在 LINQ 选择方法中使用 URL.Action

asp.net-mvc - 如何让 DataAnnotations 持久化到 ViewModels