runtime icon indicating copy to clipboard operation
runtime copied to clipboard

There are some exception when publish a app in .net core 7

Open f3404923 opened this issue 4 years ago • 3 comments

My development enviroment: OS: WIN10 64BIT VS: VS2022 .NET 7 APP: windows console app Targe PC: x64 windows

I create a simple console app that it can run in debug and release mode, but it can not run and occured exception when I publish to a AOT app. How to solve this issue?

The detail exception as below:

Unhandled Exception: System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'ConsoleApp1.TestObject'. Path: $ | LineNumber: 1 | BytePositionInLine: 3.
 ---> System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'ConsoleApp1.TestObject'.
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(ReadStack&, Utf8JsonReader&, NotSupportedException) + 0x1fe
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader&, Type, JsonSerializerOptions, ReadStack&, T&) + 0x570
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader&, Type, JsonSerializerOptions, ReadStack&, T&) + 0x1ec
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader&, JsonSerializerOptions, ReadStack&) + 0x348
   at System.Text.Json.JsonSerializer.ContinueDeserialize[TValue](ReadBufferState&, JsonReaderState&, ReadStack&, JsonTypeInfo) + 0x105
   at System.Text.Json.JsonSerializer.<ReadFromStreamAsync>d__76`1.MoveNext() + 0x3b1
--- End of stack trace from previous location ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb6
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x42
   at Program.<<Main>$>d__0.MoveNext() + 0x1e5

--- End of stack trace from previous location ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb6
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x42
   at Program.<Main>(String[]) + 0x20
   at ConsoleApp1!<BaseAddress>+0x2dc56b

This is code of a object:

  public class TestObject
    {
        public string Name { get; set; }
        public int Age { get; set; }
        [JsonConstructor]
        public TestObject() { }
    }

This is code of Program.cs

using System.Text.Json;

using (var sr=new StreamReader("DataItems.json"))
{
    var testObjs = await JsonSerializer.DeserializeAsync<TestObject>(sr.BaseStream);
    if(testObjs != null)
    {
        Console.WriteLine(testObjs.Name);
        Console.WriteLine(testObjs.Age);
    }
    Console.WriteLine("Test end.");
}

This is code of ConsoleApp.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
	  <PublishAot>true</PublishAot>
	  <PublishTrimmed>true</PublishTrimmed>	 
  </PropertyGroup>

  <ItemGroup>
    <None Update="DataItems.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

f3404923 avatar Nov 28 '22 05:11 f3404923

Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis See info in area-owners.md if you want to be subscribed.

Issue Details

My development enviroment: OS: WIN10 64BIT VS: VS2022 .NET 7 APP: windows console app Targe PC: x64 windows

I create a simple console app that it can run in debug and release mode, but it can not run and occured exception when I publish to a aot app. How to solve this issue?

The detail exception as below:

Unhandled Exception: System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'ConsoleApp1.TestObject'. Path: $ | LineNumber: 1 | BytePositionInLine: 3. ---> System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'ConsoleApp1.TestObject'. --- End of inner exception stack trace --- at System.Text.Json.ThrowHelper.ThrowNotSupportedException(ReadStack&, Utf8JsonReader&, NotSupportedException) + 0x1fe at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader&, Type, JsonSerializerOptions, ReadStack&, T&) + 0x570 at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader&, Type, JsonSerializerOptions, ReadStack&, T&) + 0x1ec at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader&, JsonSerializerOptions, ReadStack&) + 0x348 at System.Text.Json.JsonSerializer.ContinueDeserialize[TValue](ReadBufferState&, JsonReaderState&, ReadStack&, JsonTypeInfo) + 0x105 at System.Text.Json.JsonSerializer.<ReadFromStreamAsync>d__761.MoveNext() + 0x3b1 --- End of stack trace from previous location --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb6 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x42 at Program.<

$>d__0.MoveNext() + 0x1e5 --- End of stack trace from previous location --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb6 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x42 at Program.
(String[]) + 0x20 at ConsoleApp1!+0x2dc56b

This is code of a object:

  public class TestObject
    {
        public string Name { get; set; }
        public int Age { get; set; }
        [JsonConstructor]
        public TestObject() { }
    }

This is code of Program.cs `using System.Text.Json;

using (var sr=new StreamReader("DataItems.json")) { var testObjs = await JsonSerializer.DeserializeAsync(sr.BaseStream); if(testObjs != null) { Console.WriteLine(testObjs.Name); Console.WriteLine(testObjs.Age); } Console.WriteLine("Test end."); }`

This is code of ConsoleApp.csproj `

Exe net7.0 enable enable true true PreserveNewest `
Author: f3404923
Assignees: -
Labels:

area-System.Text.Json, untriaged

Milestone: -

ghost avatar Nov 28 '22 05:11 ghost

You should see warning like this when publishing the application:

Program.cs(6): AOT analysis warning IL3050: Program.<<Main>$>d__0.MoveNext(): Using member 'System.Text.Json.J
sonSerializer.DeserializeAsync<TestObject>(Stream,JsonSerializerOptions,CancellationToken)' which has 'RequiresDynamicC
odeAttribute' can break functionality when AOT compiling. JSON serialization and deserialization might require types th
at cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for nat
ive AOT applications.

This warning is referring to the problem that you are seeing. The default reflection-based System.Text.Json does not work with trimming and native AOT compilation. System.Text.Json source generation has to be used for native AOT applications instead.

Example for how to use System.Text.Json source generation: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation#complete-program-example

Add this to Program.cs:

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(TestObject))]
internal partial class MyJsonContext : JsonSerializerContext
{
}

and change the DeserializeAsync call to JsonSerializer.DeserializeAsync<TestObject>(sr.BaseStream, MyJsonContext.Default.TestObject)

The warning should be gone one you do this. It is a good idea to make sure that there are no warnings when you are publishing native AOT applications.

jkotas avatar Nov 28 '22 06:11 jkotas

@jkotas Yes, it is working. Thanks so much. I'll close this ticket.

f3404923 avatar Nov 29 '22 00:11 f3404923