可以在Asp.Net Core中使用Swagger来生成非MVC控制器的类的文档

时间:2017-10-23 11:35:14

标签: c# swagger asp.net-core-2.0 swashbuckle

我一直在寻找一些没有太多运气的线索。 看起来mvc core 2停止使用IApiExplorer我可以找到一些例子,所以我不确定从哪里开始。

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

我有自定义属性装饰的类(简化):

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

其中attribute属性定义为:

[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控制器。

非常感谢

2 个答案:

答案 0 :(得分:1)

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

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

以下是GitHub上的完整代码SwaggerConfig.cs

对你来说可能略有不同,因为我不是net-core

答案 1 :(得分:0)

我现在已在Routable Dto solution中集成了对此问题的答案,请参阅RoutableDtoSwaggerGenerator类。

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

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

希望这可以帮助某人并节省一些时间。