AddSwaggerGen - create object in swagger.json for not used DTO

94 Views Asked by At

I use services.AddSwaggerGen() to create a 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",

       });
});

This is working so far. But now, I have a DTO, which is not used explizit in a Controller. And this DTO is not added as an object to the swagger.json. Is there a possibility to configure, that this DTO will also be included in the swagger.json?

1

There are 1 best solutions below

0
PrinceEntree8 On

I think you should add an attribute to the DTOs that are not referenced elsewhere. Please follow the documentation by just adding the package Swashbuckle.AspNetCore.Annotations and then adding to your DTO the SwaggerSchemaAttribute as follows:

[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; }
}

Please notice that it is a good practice to describe controllers and models with attributes as they will be added to the embedded webpage as well as in your swagger.json file