runtime: System.Text.Json source generator fails if [Required(ErrorMessage = "...")] attribute is present.
Description
I tried to use the Json source generator with a class which has a [Required] attribute with an error message, but the generator succeeds only when the ErrorMessage is not specified. I tried it with other Validation attributes (StringLength, Range), and I got the same result.
Reproduction Steps
Add the following two classes in a .NET 6.0 project, then try to build it.
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
public class TestDto
{
[Required(ErrorMessage = "asdf")]
public string Name { get; set; }
}
[JsonSerializable(typeof(TestDto))]
public partial class Serializers : JsonSerializerContext
{
}
Expected behavior
The source generator should generate the properties and the build should succeed.
Actual behavior
The source generator and the build fails and I get an error in the Output window:
Build started...
1>------ Build started: Project: SystemTextJsonTest, Configuration: Debug Any CPU ------
1>CSC : warning CS8785: Generator 'JsonSourceGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'InvalidOperationException' with message 'Sequence contains no elements'
1>D:\src\SystemTextJsonTest\SystemTextJsonTest\TestDto.cs(11,22,11,33): error CS0534: 'Serializers' does not implement inherited abstract member 'JsonSerializerContext.GetTypeInfo(Type)'
1>D:\src\SystemTextJsonTest\SystemTextJsonTest\TestDto.cs(11,22,11,33): error CS0534: 'Serializers' does not implement inherited abstract member 'JsonSerializerContext.GeneratedSerializerOptions.get'
1>Done building project "SystemTextJsonTest.csproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Regression?
No response
Known Workarounds
Remove the ErrorMessage, ErrorMessageResourceName and ErrorMessageResourceType properties from the validation attributes.
Configuration
.NET 6.0.100 Microsoft Windows [Version 10.0.19043.1348] x64
Other information
No response
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 2
- Comments: 15 (12 by maintainers)
I’ve just ran into this issue as well. I’m able to repro the issue in 6.0.1 as well as 6.0.2.
Easy repro here, switching to 6.0.1 of STJ still reproduces the issue. https://github.com/JakeYallop/JsonSerializerContextInvalidOperationExceptionRepro
As a workaround for the short term, I’ve added an explicit reference to version 7.0.0-preview.2.22152.2 of STJ in my .NET 6 project which includes the fix made above (I usually just use the in-box version, rather than an explicit reference).
Will this fix make it into a 6.0.x version of the STJ package in future?
Yes, see https://github.com/dotnet/runtime/issues/58770
I’m not sure if this issue should still be open - it seems like this is fixed in .NET 7.0.