Asp.Net Core 中的 Swagger 是否可以为 类 生成非 MVC 控制器的文档

Can Swagger in Asp.Net Core be made to produce documentation for classes that are not MVC Controllers

我一直在寻找这方面的一些线索,但运气不佳。 看起来 mvc core 2 停止使用我可以找到一些示例的 IApiExplorer,所以我不确定从哪里开始。

在我的核心 asp.net api 应用程序中,我有处理许多 api 调用的通用处理程序。因此,我需要从 类 生成表示 api 查询和命令的 swagger 文档,而不是读取 MVC 控制器的属性。

我有 类 由自定义属性装饰,如下(简化):

[ApiDriver("GetSomeResult",ApiType.Query, ApiHttpMethod.Get)]
public class MyQueryClass
{
    public string MyProperty{ get; set; }
}

其中属性定义为:

[AttributeUsage(AttributeTargets.Class)]
public class ApiDriverAttribute: Attribute
{
    public ApiDriverAttribute(string apiName, ApiType apiType, ApiHttpMethod httpMethod)
    {
        ApiName = apiName;
        ApiType = apiType;
        ApiHttpMethod = httpMethod;
    }

    public string ApiName { get; set; }
    public ApiType ApiType { get; set; }
    public ApiHttpMethod ApiHttpMethod { get; set; }
}


public enum ApiType { Command, Query}
public enum ApiHttpMethod { Post, Get }

所以我需要大摇大摆地定位(或者我需要以某种方式提供有关数据)类 以这种方式归因而不是转到 MVC 控制器。

非常感谢

以下是我将模型注入文档的方式:

private class ApplyDocumentVendorExtensions : IDocumentFilter
{
    public void Apply(SwaggerDocument sd, SchemaRegistry sr, IApiExplorer ae)
    {
        sr.GetOrRegister(typeof(ExtraType));
        //sr.GetOrRegister(typeof(BigClass));        
    }
}

这是 GitHub SwaggerConfig.cs

上的完整代码

对你来说可能略有不同,因为我不是网络核心

我现在已经在 Routable Dto solution 中集成了这个问题的答案,请参阅 RoutableDtoSwaggerGenerator class。

答案相对简单。我必须创建一个 IDocumentFilter 的实现,并从我自己的路由存储库中填充 swagger 文档路径、操作、参数和响应。

然后我所要做的就是在 StartUp 的整体 SwaggerGen 注册中注册我的过滤器。

希望这对某人有所帮助并节省一些时间。