简体   繁体   中英

How to resolve Swashbuckle/Swagger -UI model naming issue for generics?

I want to clean the names of the models in the swagger ui for my webapi.

The issue is that when I define a response type on my endpoint, and that type is a generic, it gets named in such a way that if one were to use a swagger-gen tool like NSwag, the models gets the worst names, (as they're based on the swagger, I'd like to define how the model is named).

This is the response attribute:

[ProducesResponseType(typeof(BulkUpsertResponse<AccountingCode>), StatusCodes.Status200OK)]

This is the resultant name: Company.IntegrationApi.Api.Models.Responses.BulkUpsertResponse1[[Company.IntegrationApi.Api.Models.AccountingParameters.AccountingCode, Company.IntegrationApi.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

What NSwag makes it to be: BulkUpsertResponse_1OfOfAccountingCodeAndApiAnd_0AndCulture_neutralAndPublicKeyToken_null

What i'd like the name to be is: BulkUpsertResponse<AccountingCode>

I've tried to find an attribute or tag to define the name, and it's not feasable to make the generics into "hard types" as it's hundreads of uses.

How can I specify the name exactly, or what work-arounds can I use to solve my issue?

Add Swashbuckle.Swagger NuGet package. Then in your init method use

CustomSchemaIds(i => i.FriendlyId(true));

See example below:D

using Swashbuckle.Swagger;
///then in configure services..

services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo
                    {
                        Version = "v1",
                        Title = "Your API",
                        Description = "Interfaces available for API",
                    });
                    c.CustomSchemaIds(x => x.FullName);
                    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey,
                        Scheme = "Bearer"
                    });
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    c.IncludeXmlComments(xmlPath);
                    c.CustomSchemaIds(i => i.FriendlyId(true));


                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM