使用ServiceStack.Api.OpenApi

时间:2019-08-06 00:48:54

标签: servicestack openapi servicestack-openapi

当我在SwaggerHub上生成API规范时,可以声明架构,包括如下用户友好示例:

components:
  schemas:
    Job:
      type: object
      required:
        - position
        - department
        - startDate
      properties:
        jobId:
          type: integer
          format: int32
        position:
          type: string
          example: Copy Boy III
        department:
          type: string
          example: Legal
        startDate:
          type: string
          format: date
          example: '2019-10-01'

我不知道如何使用ServiceStack OpenAPI中的属性生成相同的内容。是否在“响应” DTO上放置属性?还是我的类型?我找不到与“示例”字段相对应的任何属性。

我尝试在响应DTO和响应所绑定的类型上都使用[ApiMember],它看起来像是最接近的可能选项,但是似乎没有什么不同。我尝试过一些方法,只是希望看到Swagger UI有所更改,但都没有用:

// In the DTO
public class JobResponse
{
    [ApiMember(Name = "Job", DataType = "array")] // Will this do anything?
    public Job Job { get; set; }
    public ResponseStatus ResponseStatus { get; set; } // inject structured errors
}

// In the Type
public class Job : IEntity
{
    [Required][DataMember(Name = "jobId")]
    public int Id { get; set; }
    [ServiceStack.ApiMember(Name = "test", DataType = "string", IsRequired = true)] // Will this do anything?
    public string Position { get; set; }
    public string Department { get; set; }
    public DateTime? StartDate { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您通常会使用Open API Attributes来定制在您的服务的生成的/openapi规范中返回的元数据。

描述操作的属性应该在请求DTO 上,这是带注释的请求DTO 的示例:

[Api("Service Description")]
[Tag("Core Requests")]
[ApiResponse(HttpStatusCode.BadRequest, "Your request was not understood")]
[ApiResponse(HttpStatusCode.InternalServerError, "Oops, something broke")]
[Route("/swagger/{Name}", "GET", Summary = "GET Summary", Notes = "Notes")]
[Route("/swagger/{Name}", "POST", Summary = "POST Summary", Notes="Notes")]
public class MyRequestDto
{
    [ApiMember(Name="Name", Description = "Name Description",
        ParameterType = "path", DataType = "string", IsRequired = true)]
    [ApiAllowableValues("Name", typeof(Color))] //Enum
    public string Name { get; set; }
}

如果您要覆盖默认的DTO类型属性,也可以在其上使用[ApiMember]

只要您需要对生成的/openapi进行更细粒度的控制,就可以在OpenApiFeature插件上使用Operation Filters,例如:

Plugins.Add(new OpenApiFeature
{
    OperationFilter = (verb, operation) => operation.Tags.Add("all operations")
});

可用的配置选项:

  • ApiDeclarationFilter-允许修改返回的OpenAPI json的最终结果
  • OperationFilter-允许修改操作
  • SchemaFilter-允许修改用户类型的OpenAPI架构
  • SchemaPropertyFilter-允许在中修改属性声明 OpenAPI模式