我使用
services.AddSwaggerGen()
创建 swagger.json:
services.AddSwaggerGen(c =>
{
c.CustomOperationIds(apiDesc => {
if (apiDesc.TryGetMethodInfo(out var methodInfo)) {
if (methodInfo.GetCustomAttributes(typeof(HttpMethodAttribute)).FirstOrDefault() is HttpMethodAttribute attr) {
if (!string.IsNullOrEmpty(attr.Template)) {
return attr.Template;
}
}
}
return $"{apiDesc.HttpMethod.Substring(0, 1)}{apiDesc.HttpMethod.Substring(1, apiDesc.HttpMethod.Length -1).ToLower()}";
});
c.SwaggerDoc("v1", new OpenApiInfo() {
Title = "Time API",
Version = "v1",
});
});
到目前为止,这是有效的。但现在,我有一个 DTO,它没有在控制器中明确使用。并且此 DTO 不会作为对象添加到 swagger.json 中。是否可以配置该 DTO 也包含在 swagger.json 中?
我认为您应该向其他地方未引用的 DTO 添加一个属性。 请遵循 文档,只需添加包
Swashbuckle.AspNetCore.Annotations
,然后将 SwaggerSchemaAttribute
添加到您的 DTO,如下所示:
[SwaggerSchema(Required = new[] { "Description" })]
public class Product
{
[SwaggerSchema("The product identifier", ReadOnly = true)]
public int Id { get; set; }
[SwaggerSchema("The product description")]
public string Description { get; set; }
[SwaggerSchema("The date it was created", Format = "date")]
public DateTime DateCreated { get; set; }
}
请注意,用属性描述控制器和模型是一个很好的做法,因为它们将被添加到嵌入式网页以及您的
swagger.json
文件中