我有一個 .NET Framework 4.8 / AngularJS 應用程式,我正在嘗試升級到 .NET 6,以便我可以開始嘗試更新的前端框架(如 Blazor)。升級進展順利,但從 Angular JS 代碼呼叫我的 API 方法之一時,我始終看到此錯誤:
System.NotSupportedException: Serialization and deserialization of 'System.IntPtr' instances are not supported. Path: $.TargetSite.MethodHandle.Value.
---> System.NotSupportedException: Serialization and deserialization of 'System.IntPtr' instances are not supported.
at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, NotSupportedException ex)
at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: Negotiate TlRMTVNTUAADAAAAGAAYAHgAAABgAWABkAAAAAAAAABYAAAADgAOAFgAAAASABIAZgAAABAAEADwAQAAFYKI4goAYUoAAAAPV7Hpy762wOgD8P0Vp4p25WsAawBvAHoAbABlAHIASwBLAE8AWgBMAEUAUgAtAEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyKkYMRt BEmGGiFVayCimwEBAAAAAAAAsRKCqZ8i2AHdnAn8ozInsAAAAAACABAAUABSAE8ATQBPAEQARQBMAAEAEgBLAEsATwBaAEwARQBSAC0ATAAEACIAYwBvAHIAcAAuAHAAcgBvAG0AbwBkAGUAbAAuAGMAbwBtAAMANgBLAEsATwBaAEwARQBSAC0ATAAuAGMAbwByAHAALgBwAHIAbwBtAG8AZABlAGwALgBjAG8AbQAFACIAYwBvAHIAcAAuAHAAcgBvAG0AbwBkAGUAbAAuAGMAbwBtAAcACACxEoKpnyLYAQYABAACAAAACAAwADAAAAAAAAAAAQAAAAAgAABZ/aEtx5BWovcqYmfEANzjrij27KQ UdanKJzMjBJr2QoAEAAAAAAAAAAAAAAAAAAAAAAACQAcAEgAVABUAFAALwBsAG8AYwBhAGwAaABvAHMAdAAAAAAAAAAAAKxoJoGhKPec1JQ2hdsVSsQ=
Connection: keep-alive
Content-Length: 346
Content-Type: application/json;charset=UTF-8
Cookie: ai_user=r bRv|2022-01-12T04:50:58.222Z
Host: localhost:42721
Referer: http://localhost:42721/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Origin: http://localhost:42721
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
我對這個錯誤感到困惑。API 方法如下所示:
[HttpPost]
public IActionResult Validate([FromBody] ValidationDto dto)
{
try
{
...
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError, ex.InnermostException());
}
}
該類ValidationDto如下所示:
public class ValidationDto
{
public Guid GuidProperty { get; set; }
public DateTime? NullableDateTimeProperty { get; set; }
public int IntegerProperty { get; set; }
public ValidationType EnumProperty { get; set; }
public bool BooleanProperty { get; set; }
}
ValidationType列舉看起來像這樣:
public enum ValidationType
{
FirstType,
SecondType,
ThirdType,
}
我指定的唯一 JSON 選項如下:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
在哪里System.Text.Json找到IntPtr它無法反序列化的?
uj5u.com熱心網友回復:
您的代碼在序列化而不是反序列化期間失敗,因為您正在捕獲一些內部例外并嘗試通過在此處回傳它來使用 System.Text.Json 對其進行序列化:
return StatusCode((int)HttpStatusCode.InternalServerError, ex.InnermostException());
不幸的是,System.Text.Json 不支持例外序列化,請參閱System.Text.Json - 無法序列化例外 #43026以及演示小提琴https://dotnetfiddle.net/RrlPQB。它特別試圖序列化TargetSite.MethodHandle.Value實際上是一個IntPtr.
如果你真的需要回傳所有例外資料,你可以撰寫一個自定義JsonConverter<Exception>的. 但是,將必要的資訊作為字串或 DTO 回傳會更容易,如下所示:
return StatusCode((int)HttpStatusCode.InternalServerError, ex.InnermostException().Message);
要么
return StatusCode((int)HttpStatusCode.InternalServerError, ex.InnermostException().ToString());
甚至是像這樣的匿名型別 DTO:
return StatusCode((int)HttpStatusCode.InternalServerError, new { ex.InnermostException().Message, StackTrace = ex.InnermostException().StackTrace?.ToString()} );
將例外作為 JSON 訊息回傳具有用于自定義例外回傳方式的附加選項。
uj5u.com熱心網友回復:
首先,我建議您使用 Newtonsoft.Json 來避免所有這些奇怪的錯誤
using Newtonsoft.Json.Serialization;
builder.Services.AddControllers (
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
如果您決定使用 Newtonsoft,則必須將這些屬性添加到 enum
public enum ValidationType
{
[EnumMember(Value = "FirstType")]
FirstType,
[EnumMember(Value = "SecondType")]
SecondType,
ThirdType,
}
如果你繼續使用 text.json 試試他們的列舉轉換器
JsonSerializerOptions options = new JsonSerializerOptions{
Converters ={
new JsonStringEnumConverter( JsonNamingPolicy.CamelCase)
},
};
JsonSerializer.Serialize(data, options);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426959.html
標籤:C# asp.net 核心 .net-6.0 system.text.json
