question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Swashbuckle.AspNetCore.Filters throws an exception when trying to use System.Text.Json.Serialization.JsonStringEnumConverter

See original GitHub issue

VERSION:

Swashbuckle.AspNetCore Version=“5.0.0-rc5” Swashbuckle.AspNetCore.Filters Version=“5.0.0-rc9” Swashbuckle.AspNetCore.Swagger Version=“5.0.0-rc5” Swashbuckle.AspNetCore.SwaggerGen Version=“5.0.0-rc5” Swashbuckle.AspNetCore.SwaggerUi Version=“5.0.0-rc5”

STEPS TO REPRODUCE:

I’m sorry I wanted to create a minimal sample repository so you guys can just clone and check but at my company for security reasons I can’t push anything on Github.

Create an ASP.NET 3.1 project.

Here is the Startup.cs

public class Startup
{
	public Startup(IConfiguration configuration)
	{
		Configuration = configuration;
	}

	public IConfiguration Configuration { get; }

	public void ConfigureServices(IServiceCollection services)
	{
		services.AddControllers();

		services.AddVersionedSwagger();
	}

	public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider)
	{
		app.UseRouting();

		app.UseVersionedSwagger(provider);

		app.UseEndpoints(endpoints =>
		{
			endpoints.MapControllers();
		});
	}
}

A VersionedSwaggerExtensions.cs file declaring some extension methods

public static class VersionedSwaggerExtensions
    {
        public static IServiceCollection AddVersionedSwagger(this IServiceCollection services)
        {
            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });

            services.AddVersionedApiExplorer(o => o.GroupNameFormat = "'V'VVV");

            var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();

            services.AddSwaggerGen(options =>
            {
                var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();

                foreach (var apiVersion in provider.ApiVersionDescriptions)
                {
                    ConfigureVersionedDescription(options, apiVersion);
                }
            });

            services.AddSwaggerExamplesFromAssemblyOf<FooRequestExampleProvider>();

            return services;
        }

        private static void ConfigureVersionedDescription(SwaggerGenOptions options, ApiVersionDescription apiVersion)
        {
            var descriptions = new Dictionary<string, string>
                {
                    { "1.0", "Version 1.0 of my test API" }
                };

            var apiVersionName = apiVersion.ApiVersion.ToString();
            options.SwaggerDoc(apiVersion.GroupName,
                new OpenApiInfo()
                {
                    Title = "Just a test API",
                    Contact = new OpenApiContact()
                    {
                        Name = "Jérôme MEVEL"
                    },
                    Version = apiVersionName,
                    Description = descriptions[apiVersionName]
                });
        }

        public static IApplicationBuilder UseVersionedSwagger(this IApplicationBuilder app, IApiVersionDescriptionProvider provider)
        {
            app.UseSwagger();

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

            return app;
        }

And finally a FooController

[ApiController]
[Route("[controller]")]
public class FooController : ControllerBase
{
	/// <summary>
	/// Just a test Method
	/// </summary>
	/// <param name="fooParams">My Params</param>
	/// <returns></returns>
	[HttpGet("Foo")]
	[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(FooResult))]
	[SwaggerRequestExample(requestType: typeof(FooQuery), examplesProviderType: typeof(FooRequestExampleProvider), jsonConverter: typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
	[SwaggerResponseExample(statusCode: 200, examplesProviderType: typeof(FooResponseExampleProvider), jsonConverter: typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
	public FooResult Foo([FromQuery]FooQuery fooParams)
	{
		return new FooResult()
		{
			Result = "Success"
		};
	}
}

EXPECTED RESULT:

Swagger generates the API documentation along with query examples

ACTUAL RESULT:

options.SwaggerEndpoint throws the following exception (didn’t include the full stacktrace)

System.InvalidCastException HResult=0x80004002 Message=Unable to cast object of type ‘System.Text.Json.Serialization.JsonStringEnumConverter’ to type ‘Newtonsoft.Json.JsonConverter’. Source=Swashbuckle.AspNetCore.Filters StackTrace: at Swashbuckle.AspNetCore.Filters.SwaggerRequestExampleAttribute…ctor(Type requestType, Type examplesProviderType, Type contractResolver, Type jsonConverter)

ADDITIONAL DETAILS

Here is the StackOverflow question I created

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
mattfrearcommented, Dec 21, 2022

Hi, I’m the author of https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters

  1. Is this still an issue with the latest version of the above NuGet?
  2. If so - then it should be logged at the above GitHub project and not here. This issue here can be closed.
1reaction
mzhukovscommented, Dec 2, 2020

Yes I am seeing the same thing, i.e. that the attribute for System.Text.Json (not Newtonsoft) with [JsonConverter(typeof(JsonStringEnumConverter))] is not taken into account

Update: added this to Startup.cs and it is working as expected, fyi @jmevel :

        services.AddControllersWithViews() 
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // this was the key
            });
Read more comments on GitHub >

github_iconTop Results From Across the Web

Swashbuckle.AspNetCore.Filters throws an exception ...
Filters throws an exception when trying to use System.Text.Json. ... Text.Json.Serialization.JsonStringEnumConverter' to type 'Newtonsoft.
Read more >
Swashbuckle.AspNetCore.Filters throws an exception ...
Swashbuckle.AspNetCore.Filters throws an exception when trying to use System.Text.Json.Serialization.JsonStringEnumConverter.
Read more >
Migrate from Newtonsoft.Json to System.Text.Json - .NET
The System.Text.Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). The System.
Read more >
Data binding and serialization issue with System.Text.Json ...
Hi,I am using System.Text.Json and Kendo UI in a .NET Core 6.0 project. I have followed this article in order to solve the...
Read more >
Override System.Text.Json.JsonSerializer error message in ...
When a client sends the wrong value type for an input, the serializer in SystemTextJsonInputFormatter throws an exception and the above error message...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found