2016-01-25 8 views
7

Come annotare le mie azioni WebAPI ASP.NET in modo che i metadati dello swagger includano i tipi di contenuto supportati dalle mie risorse?Swashbuckle Swagger - Come annotare i tipi di contenuto?

In particolare, voglio la documentazione per dimostrare che una delle mie risorse possono restituire il 'originale' application/json e application/xml ma anche ora restituisce un nuovo formato, application/vnd.blah+json o +xml.

+0

Shashbuckle 5 dovrebbe occuparsi di questo per voi se si registra MediaTypeFormatter durante la configurazione Web Api. –

+0

Grazie. Sembra intelligente, ma lo voglio per azione/percorso. –

+1

Penso che tu debba solo aggiungerlo come formattatore nel tuo webconfig - questo è globale, comunque, non in base all'azione. Quello che potevi fare era creare il tuo file di operazioni personali e applicarlo solo a quelle operazioni che restituiscono il nuovo formato – VisualBean

risposta

7

Quello che devi fare è questo; Swagger spec: è necessario aggiungere la risposta di tipo all'elenco dei tipi di risposta per tale operazione

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

Questo può essere fatto con un OperationFilter

Pseudo codice in arrivo !!!

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

l'OperationId può essere impostato attraverso il [SwaggerOperation("myCustomName")] annotazione.

Applicare quindi l'operationsFilter nelle swaggerConfig.cs

c.OperationFilter<CustomResponseType>(); 

Nota: invece di operation.operationId == "myCustomName" si potrebbe fare per una particolare rotta o qualsiasi altra cosa in fondo. ApiDescription dà un sacco di informazioni sul contesto.

26

estensione @ risposta di VisualBean

Il metodo API di un controller è possibile utilizzare il seguente codice per impostare un attributo del tipo:

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

Nota: 'Exclusive = true' rimuoverà tutti gli altri tipi di contenuto, altrimenti, utilizzando il nuovo attributo, verrà aggiunto un nuovo tipo di contenuto di risposta nell'interfaccia utente di Swagger. NON modificherà il tuo Controller o API solo la documentazione.

SwaggerConfig.cs

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

SwaggerReponseContentTypeAttribute.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); 
     } 
    } 
} 
5

@ La risposta di OzBob presuppone che tu voglia solo aggiungere un singolo attributo a un metodo. Se si desidera aggiungere e documentare più di un tipo di contenuto per lo stesso metodo si può utilizzare il seguente:

SwaggerReponseContentTypeAttribute.cs

/// <summary> 
/// SwaggerResponseContentTypeAttribute 
/// </summary> 
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 
public 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>(); 

     foreach (var requestAttribute in requestAttributes) 
     { 
      if (requestAttribute.Exclusive) 
      { 
       operation.produces.Clear(); 
      } 
      operation.produces.Add(requestAttribute.ResponseType); 
     } 
    } 
} 

Nota che quando si dispone di più attributi lo stesso metodo e si desidera sostituire i tipi di contenuto già esistenti, è necessario impostare Exclusive = true solo sul primo attributo. Altrimenti non otterrai tutti gli attributi nella documentazione.

+1

Dovendo inserire Exclusive = true, il primo attributo non è ovvio per lo sviluppatore. Penso che l'ordine degli attributi non dovrebbe influenzare l'output. L'ordinamento dell'elenco di attributi nel filtro dovrebbe rimuovere la limitazione: requestAttributes.OrderByDescending (a => a.Exclusive) –

Problemi correlati