Asp.net-Web-Api2

Swashbuckle Swagger - 如何註釋內容類型?

  • January 25, 2016

如何註釋我的 ASP.NET WebAPI 操作,以便 swagger 元數據包含我的資源支持的內容類型?

具體來說,我希望文件顯示我的一個資源可以返回“原始” application/jsonapplication/xml但現在也可以返回新格式,application/vnd.blah+json或者+xml.

你需要做的是這個; Swagger 規範: 您需要將您的響應類型添加到該操作的響應類型列表中:

"produces": [
           "application/json",
           "text/json"
           ],

這可以通過 OperationFilter 來完成。

虛擬碼傳入!!!

public class CustomResponseType : IOperationFilter
{        
   public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
   {            
           if (operation.operationId == "myCustomName")
           {
               operation.produces.Add("application/vnd.blah+json");
           }            
   }      
}

OperationId 可以通過[SwaggerOperation("myCustomName")]註解設置。

然後在 swaggerConfig.cs 中應用 operationsFilter:

c.OperationFilter<CustomResponseType>();

注意:operation.operationId == "myCustomName" 您基本上可以為特定路線或其他任何事情做而不是這樣做。ApiDescription 提供了很多關於上下文的資訊。

擴展@VisualBean 的答案

在控制器的 API 方法中,您可以使用下面的程式碼來設置屬性,例如:

[SwaggerResponseContentType(responseType:"application/pdf", Exclusive=true)]
public HttpResponseMessage GetAuthorityForm(string id)
{
....

注意:“Exclusive=true”將刪除所有其他內容類型,否則使用新屬性將在 Swagger UI 下拉列表中添加新的響應內容類型。它不會修改您的控制器或 API,只會修改文件。

SwaggerConfig.cs

GlobalConfiguration.Configuration
           .EnableSwagger(c =>
// Set filter to apply Custom Content Types to operations
//
c.OperationFilter<ResponseContentTypeOperationFilter>();

SwaggerResponseContentTypeAttribute.cs

/// <summary>
/// SwaggerResponseContentTypeAttribute
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SwaggerResponseContentTypeAttribute : Attribute
{
   /// <summary>
   /// SwaggerResponseContentTypeAttribute
   /// </summary>
   /// <param name="responseType"></param>
   public SwaggerResponseContentTypeAttribute(string responseType)
   {
       ResponseType = responseType;
   }
   /// <summary>
   /// Response Content Type
   /// </summary>
   public string ResponseType { get; private set; }

   /// <summary>
   /// Remove all other Response Content Types
   /// </summary>
   public bool Exclusive { get; set; }
}

ResponseContentTypeOperationFilter.cs

public class ResponseContentTypeOperationFilter : IOperationFilter
{
   public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
   {
       var requestAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseContentTypeAttribute>().FirstOrDefault();

       if (requestAttributes != null)
       {
           if (requestAttributes.Exclusive)
               operation.produces.Clear();

           operation.produces.Add(requestAttributes.ResponseType);
       }
   }
}

引用自:https://stackoverflow.com/questions/34990291