Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException: Can't use schemaId .. The same schemaId is already used for type

I receive the following error.

InvalidOperationException: Can't use schemaId "$Registration" for type "$PortalService.Models.Registration". The same schemaId is already used for type "$PortalService.Models.Registration"

I have tried the suggestions in the following link without any succcess.

swagger error: Conflicting schemaIds: Duplicate schemaIds detected for types A and B

I only have one Registration class in models. I have tried renaming the class without success.

I am using an OData .Net Core 3.1 project.

Configure Swagger is below

 services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
            services.AddSwaggerGen(c =>
            {
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n 
                      Enter 'Bearer' [space] and then your token in the text input below.
                      \r\n\r\nExample: 'Bearer 12345abcdef'",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                  {
                    {
                      new OpenApiSecurityScheme
                      {
                        Reference = new OpenApiReference
                          {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                          },
                          Scheme = "oauth2",
                          Name = "Bearer",
                          In = ParameterLocation.Header,

                        },
                        new List<string>()
                      }
                    });
            });

Use Swagger is below

  app.UseSwagger(c =>
            {
                //c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = basepath);

                 
                c.PreSerializeFilters.Add((swaggerDoc, httpReq) => {
                    Microsoft.OpenApi.Models.OpenApiPaths paths = new Microsoft.OpenApi.Models.OpenApiPaths();
                    foreach (var path in swaggerDoc.Paths)
                    {
                        paths.Add(path.Key.Replace(path.Key, basepath + path.Key), path.Value);
                    }
                    swaggerDoc.Paths = paths;
                });
            });
            app.UseSwaggerUI(
                options =>
                {
                    options.RoutePrefix = string.Empty;

                    // build a swagger endpoint for each discovered API version

                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        options.SwaggerEndpoint($"{basepath}/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
                    }

                });

This appears to be related to

Swagger crashes with circular model references

I have found that if I comment out the partner back reference from registration, the error goes away but I need this reference. I am not clear how to fix the situation.

[ForeignKey("Partner")]
[DataMember(Name = "PartnerOID")]
[Column(TypeName = "VARCHAR(100)")]
public string PartnerOID { get; set; }
//public virtual Partner Partner { get; set; }
like image 543
John Bowyer Avatar asked May 19 '20 01:05

John Bowyer


3 Answers

Try this John: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1607#issuecomment-607170559 helped me.

I can understand what is happening; i have several enums with 'Status' or 'Type'. Using options.CustomSchemaIds( type => type.ToString() ); solved this.

like image 118
Erik Avatar answered Nov 11 '22 06:11

Erik


The only change needed is in your Startup.cs inside the method ConfigureServices.

You should add the following:

services.AddSwaggerGen(options =>
{
    options.CustomSchemaIds(type => type.ToString());
});
like image 66
Mauro Bilotti Avatar answered Nov 11 '22 06:11

Mauro Bilotti


I've been using options.CustomSchemaIds(type => type.ToString()); and options.CustomSchemaIds(type => $"{type.Name}_{System.Guid.NewGuid().ToString().Replace("-", "")}") to create uniqueness on schema names. Both results in longer schema names which I hate.

Here's a different approach which track the name repetition, which I prefer.

Helper class:

internal static class SwashbuckleSchemaHelper
{
   private static readonly Dictionary<string, int> _schemaNameRepetition = new Dictionary<string, int>();

   public static string GetSchemaId(Type type)
   {
      string id = type.Name;

      if (!_schemaNameRepetition.ContainsKey(id))
          _schemaNameRepetition.Add(id, 0);

      int count = (_schemaNameRepetition[id] + 1);
      _schemaNameRepetition[id] = count;

      return type.Name + (count > 1 ? count.ToString() : "");
   }
}

Usage:

options.CustomSchemaIds(type => SwashbuckleSchemaHelper.GetSchemaId(type));

This would result as below, if the class name was duplicated.

  • Invoice
  • LineItem
  • Status
  • Status2
like image 3
Dhanuka Jayasinghe Avatar answered Nov 11 '22 05:11

Dhanuka Jayasinghe