2

I've been trying to document this API with Swashbuckle.Example. I have followed this tutorial. The SwaggerResponseExample attribute works but the SwaggerRequestExample is not rendered. I have also checked the json in /docs/v1 and again the Response Example was present but not the Request Example.

What's going on? How do I debug this?

Controller.cs

[System.Web.Http.HttpPost]
[SwaggerOperation(OperationId = "SAAT_ciclotarifario_GetById")]
[SwaggerResponseExample(HttpStatusCode.OK, typeof(GrupoFtFronteiraPostResponseExamples))]
[SwaggerRequestExample(typeof(GrupoFtFronteira), typeof(GrupoFtFronteiraPostRequestExamples))]
[ActionName("GrupoFtFronteira")]
public HttpResponseMessage PostGrupoFtFronteira([FromBody] GrupoFtFronteira requestBody)
{
    try
    {
        var novoGrupoFtFronteira = _grupofronteiraNegocio.PostGrupoFtFronteira(requestBody);

        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            ReasonPhrase = "Success",
            Content = new StringContent("idGrupoFtFronteira: " + novoGrupoFtFronteira.IdGrupoftfronteira, System.Text.Encoding.UTF8, "application/json")
        };
    }
    catch (Exception e)
    {
        var msg = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            ReasonPhrase = "Internal Server Error",
            Content = new StringContent("Erro ao tentar atualizar dados. " + e.Message, System.Text.Encoding.UTF8, "application/json")
        };

        throw new HttpResponseException(msg);
    }
}

SwaggerConfig.cs

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                    c.DocumentFilter<SwaggerFilterOutControllers>();

                    c.SingleApiVersion("v1", "ons.sact.servico.controller");

                    c.ApiKey("Authorization")
                    .Description("JWT token")
                    .Name("Bearer")
                    .In("header");

                    c.OperationFilter<ExamplesOperationFilter>();
                })
            .EnableSwaggerUi(c =>
                {
                    c.EnableApiKeySupport("apiKey", "header");
                });
    }
}
Rafael
  • 191
  • 1
  • 11
  • 1
    share the `ExamplesOperationFilter` class – John Nyingi Apr 09 '22 at 04:41
  • That's actually a very interesting quesiton since I believe there isn't any! I believed this was something that came with the Nuget... I've just tried to copy and paste this [ExampleOperationFilter](https://github.com/mattfrear/Swashbuckle.Examples/blob/918142dcd0310fc3a7043d2efd317e5955e7a94c/Swashbuckle.Examples/Examples/ExamplesOperationFilter.cs), it compiled, but nothing changed in the behaviour.... – Rafael Apr 09 '22 at 15:13
  • you need to implement the Filter (`ExamplesOperationFilter`) which has your model `GrupoFtFronteira`. See this [explained answer](https://stackoverflow.com/a/49076281/7022936) – John Nyingi Apr 11 '22 at 04:02

1 Answers1

0

I found it!

It seems that I was supposed to fill the Request Type inside this foreach ( KeyValuePair<string, Swashbuckle.Swagger.Schema> definition in schemaRegistry.Definitions)

There's probably a better way around this, since this is a hardcoded solution...

Anyway, thanks a lot for those who helped me out!

SwaggerFilterOutControllers.cs

void IDocumentFilter.Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
    {
        var models = new List<string>();

        foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
        {
            Console.WriteLine(apiDescription.Route.RouteTemplate);

            if (apiDescription.RelativePathSansQueryString().StartsWith("api/v1/")
                && !(apiDescription.RelativePathSansQueryString().StartsWith("api/v1/SAAT/ciclotarifario")
                || apiDescription.RelativePathSansQueryString().StartsWith("api/v1/SAAT/GrupoFtFronteira")))
            {
                string path = "/" + apiDescription.RelativePathSansQueryString();
                swaggerDoc.paths.Remove(path);
            }
        }

        foreach ( KeyValuePair<string, Swashbuckle.Swagger.Schema> definition in schemaRegistry.Definitions)
        {
            Console.WriteLine(definition.Key);

            if (!(definition.Key.Equals("CiclotarifarioPostRequest") ||
            definition.Key.Equals("GrupoFtFronteira")
            ))
            {
                models.Add(definition.Key.ToString());
            }
        }
        foreach (string modelo in models)
        {
            swaggerDoc.definitions.Remove(modelo);
        }


        CreateHeadersDict();

        var allOtherPaths = swaggerDoc.paths
            .Select(entry => entry.Value)
            .ToList();

        foreach (var path in allOtherPaths)
        {
            AddHeadersToPath(path, HeaderType.TokenAuth);
        }
    }
Rafael
  • 191
  • 1
  • 11