Customize generated model names - Swagger UI
Asked Answered
D

4

22

I'm trying to adjust the "displayName" of the model being used in an automatically generated Swagger definition.

This will only affect the Swagger names, meaning the namespace in code would be left untouched, whilst when looking at the model from Swagger UI, you'd see a custom name.

Currently, the model name being returned from code is a namespace and looks something like this: b.c.d.e.f, I would like to add an attribute to the code and "mask" the name for the Swagger docs, so that when the documentation / Swagger definition gets generated it'll be displayed as CustomSwaggerName rather.

I have a few API's (C#) using tools that include Swashbuckle (preferred) and SwaggerGen, but right now, I'd just like to get it working in either, if at all possible.

I've tried using attributes that seem to look correct:

[ResponseType(typeof(Company)),DisplayName("NewCompany")]
[SwaggerResponse(200,"NewCompany",typeof(object))]

With no luck. I also browsed the SwashBuckle git repo, hoping to find something.

An image that should help further explain what i'm trying to achieve. enter image description here

I know this might seem like a strange use case but it's for a tool being written for our AWS API Gateway automation, which will use the Swagger definition for some comparisons.

Duester answered 13/3, 2017 at 0:21 Comment(0)
E
28

(Accounts for .net core:)
I would combine the display attribute of the class with a custom swagger schema:

[DisplayName("NewCompany")]
public class Company
{
}

and then in Startup:

services.AddSwaggerGen(c =>
{                     
    c.CustomSchemaIds(x => x.GetCustomAttributes<DisplayNameAttribute>().SingleOrDefault().DisplayName);
});

see also this answer

Essonite answered 15/5, 2019 at 14:47 Comment(3)
Couldn't get this to work in .NET Core 3.1, but c.CustomSchemaIds(x => x.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault()?.DisplayName ?? x.Name) seems to work (note that the name will fallback to the class name here if the attribute is missing).Corkwood
@Corkwood I can confirm your code works for .NET 5 as well.Salenasalene
and works in .NET 8!Navaho
D
6

This is my solution, based on the suggestion provided by @AGuyCalledGerald - thanks!

It uses a more explicit custom attribute rather than DisplayName so it's clear what the attribute is being used for, and if the attribute doesn't exist it falls back to the default naming strategy.

Helpers/SwashbuckleHelpers.cs:

namespace MyProject.Helpers;

public static class SwashbuckleHelpers
{
    /// <summary>
    /// Direct copy of <see href="https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGenerator/SchemaGeneratorOptions.cs">Swashbuckle.AspNetCore.SwaggerGen.SchemaGeneratorOptions.DefaultSchemaIdSelector</see>.
    /// </summary>
    public static string DefaultSchemaIdSelector(Type modelType)
    {
        if (!modelType.IsConstructedGenericType) return modelType.Name.Replace("[]", "Array");

        var prefix = modelType.GetGenericArguments()
            .Select(genericArg => DefaultSchemaIdSelector(genericArg))
            .Aggregate((previous, current) => previous + current);

        return prefix + modelType.Name.Split('`').First();
    }
}

Attributes/CustomSwaggerSchemaIdAttribute.cs

namespace MyProject.Attributes;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class CustomSwaggerSchemaIdAttribute : Attribute
{
    public virtual string SchemaId { get; init; }

    public CustomSwaggerSchemaIdAttribute(string schemaId)
    {
        SchemaId = schemaId;
    }
}

Program.cs:

builder.Services.AddSwaggerGen(options =>
{
    ...
    options.CustomSchemaIds(t =>  t.GetCustomAttributes<CustomSwaggerSchemaIdAttribute>().SingleOrDefault()?.SchemaId ?? SwashbuckleHelpers.DefaultSchemaIdSelector(t));
});

Example usage:

[CustomSwaggerSchemaId("Customer")]
public class CustomerDto
{
    ...
}
Discrown answered 28/6, 2022 at 9:13 Comment(0)
A
2

I've used this solution with suggestion in the comment. But x.Name in case of a generic type returns too verbose name. There is an extension method from Swashbuckle.Swagger namespace which is used by Swagger by default. I've ended up with next code.

[DisplayName("NewCompany")]
public class Company
{
}

Startup.cs:

using Swashbuckle.Swagger;

services.AddSwaggerGen(c =>
{        
    c.SchemaId(x => x.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault()?.DisplayName ?? x.FriendlyId());
});
Auxochrome answered 22/7, 2022 at 13:30 Comment(0)
R
1

The answer is: use an IDocumentFilter:

private class ApplyDocumentFilter_ChangeCompany : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
    {
        if (swaggerDoc.definitions != null)
        {
            swaggerDoc.definitions.Add("Company123", swaggerDoc.definitions["Company"]);
        }
        if (swaggerDoc.paths != null)
        {
            swaggerDoc.paths["/api/Company"].get.responses["200"].schema.@ref = "#/definitions/Company123";
        }
    }
}

Here is the code: https://github.com/heldersepu/SwashbuckleTest/commit/671ce648a7cc52290b4ad29ca540b476e65240e6

And here is the final result: http://swashbuckletest.azurewebsites.net/swagger/ui/index#!/Company/Company_Get

Rahmann answered 29/6, 2017 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.