我有一个.NET Framework4.8/ AngularJS应用程序,我正在尝试升级到.NET 6,这样我就可以开始尝试更新的前端框架(比如Blazor)。升级进行得很顺利,但在从角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
?
发布于 2022-02-16 13:54:02
您的代码在序列化期间失败,而不是反序列化,因为您捕获了一些内部异常,并试图通过在这里返回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
。但是,将所需信息作为字符串或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()} );
https://stackoverflow.com/q/38664207/3744182还有其他选项可用于自定义异常的返回方式。
发布于 2022-02-15 19:53:12
首先,我建议您使用Newtonsoft.Json来避免所有这些奇怪的错误
using Newtonsoft.Json.Serialization;
builder.Services.AddControllers (
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
如果您决定继续使用text.json,请尝试它们的枚举转换器
JsonSerializerOptions options = new JsonSerializerOptions{
Converters ={
new JsonStringEnumConverter( JsonNamingPolicy.CamelCase)
},
};
JsonSerializer.Serialize(data, options);
发布于 2022-11-06 16:43:10
我试图返回整个搜索响应:
public async Task<IActionResult> Search()
{
var response = await _elasticClient.SearchAsync<User>();
return Ok(response);
}
我应该只退回文件而不是:
public async Task<IActionResult> Search()
{
var response = await _elasticClient.SearchAsync<User>();
return Ok(response.Documents);
}
https://stackoverflow.com/questions/71132371
复制相似问题