代码之家  ›  专栏  ›  技术社区  ›  Noel

ServiceStack-使用OpenApiFeature自定义生成的OpenAPI JSON

  •  2
  • Noel  · 技术社区  · 7 年前

    使用ServiceStack OpenApiFeature ,生成的 operationId 在openapi中。json文件遵循以下约定:

    [RequestName][route path slice without first path*][http verb][digit if required for uniqueness]

    这个 无第一条路径的路由路径切片* 只需删除路径中的第一项。所以如果路径是 blog/author/name ,逻辑会抓住 author/name

    这在 OpenApiService::GetOperationName method 。在某些情况下,此逻辑会在依赖 openapi.json 。例如,如果您有一个公开 GET 客户详细信息、客户摘要等的操作,详细信息请求的定义如下:

    [Api("Get a customer's details.")]
    [Route("/customer/details", "GET")]
    public class GetCustomerDetailsRequest : IReturn<GetCustomerDetailsResponse>
    { ... }
    

    路线如下(这很好): /customer/details?customerId=2

    。。。但是生成的OpenAPI 操作ID 可能是 GetCustomerDetailsRequestdetails_Get ,这不太好。

    有没有办法自定义生成的 操作ID 使用 OpenApiFeature ?如果没有,是否有其他命名约定可以维护REST风格的路由约定,但提供更好的OpenAPI 操作ID ?

    编辑: 幸亏 mythz 用于指出 ApiDeclarationFilter 。它允许您完成自定义生成的 openapi。json 。这就是我如何改变 操作ID :

    Plugins.Add(new OpenApiFeature
            {
                ApiDeclarationFilter = declaration =>
                {
                    foreach (var p in declaration.Paths)
                    {
                        foreach (var httpVerb in _httpVerbs) // _httpVerbs is just a list of http verbs
                        {
                            // retrieve the operation value using reflection and pattern matching.  This is to prevent having to use a switch statement to go through each http verb and check if it's been implemented
                            if (p.Value.GetType().GetProperty(httpVerb).GetValue(p.Value) is OpenApiOperation operation)
                            {
                                // Set the "OperationId" property using the convention [RequestClassName]_[Http Verb].  Note for simplicity here, I'm not checking for a unique operation Id.  You should do that to ensure open api compliance
                                ReflectionHelper.SetProperty($"{httpVerb}.OperationId", p.Value,
                                    $"{operation.RequestType}_{httpVerb}");
                            }
                        }
                    }
                }
            });
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   mythz    7 年前

    除了 API metadata attributes ,您可以使用 filters available ,例如:

    Plugins.Add(new OpenApiFeature
    {
        ApiDeclarationFilter = (openApiDoc) => ...,
        OperationFilter = (verb, operation) => ...,
        SchemaFilter = (schema) => ...,
        SchemaPropertyFilter = (openApiProperty) => ...,
    });