Skip to content

Can't serialize enums as string in Blazor #19086

@Regenhardt

Description

@Regenhardt

Describe the bug

Trying to serialize and object containing an enum with the Attribute [JsonConverter(typeof(JsonStringEnumConverter))] will crash.
Removing the attribute lets me easily send a poco with the enum, which gets serialized to a number as usual.

To Reproduce

Simply use the blazorwasm hosted template, add the following file to it:

using System.Text.Json.Serialization;

namespace BlazorApp3.Shared
{
	public class Poco
	{
		public string Name { get; set; }
		public int Age { get; set; }
		public MyEnum Number { get; set; }
	}

	[JsonConverter(typeof(JsonStringEnumConverter))]
	public enum MyEnum
	{
		One,
		Two,
		Three
	}
}

Also install System.Text.Json to the .Shared project.
Extend the WeatherForecastController with this method:

[HttpPost]
public Poco Post(Poco p)
{
	return p;
}

Put this at the top of the FetchData.razor for easy demo:

<button @onclick="GetPoco" >GetPoco</button>
<text>@resultString</text>

And this in the code block:

private string resultString = "";
private async Task GetPoco()
{
    var poco = new Poco()
    {
        Age = 3,
        Name = "User",
        Number = MyEnum.Three
    };
    var result = await Http.PostJsonAsync<Poco>("WeatherForecast", poco);
    resultString = $"Result:\r\nName: {result.Name}\r\nAge: {result.Age}\r\nNumber: {result.Number}";
}

Start it up and press the button.

Further technical details

  • ASP.NET Core version: 3.1, blazor 3.2 prev1
  • dotnet version: 3.1.101
  • Visual Studio Community 2019 Version 16.4.5

Metadata

Metadata

Labels

✔️ Resolution: FixedThe bug or enhancement requested in this issue has been checked-in!DoneThis issue has been fixedarea-blazorIncludes: Blazor, Razor Componentsfeature-blazor-wasmThis issue is related to and / or impacts Blazor WebAssemblyinvestigate

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions