.net core InvalidCastException使用Newtonsoft.Json反序列化SqlException

.net core InvalidCastException使用Newtonsoft.Json反序列化SqlException,.net-core,json.net,sqlexception,.net Core,Json.net,Sqlexception,反序列化包含SqlException实例的JSON字符串时出错 环境资料: -.NET核心:版本2.2 -Json:11.0.1版 结果错误: System.InvalidCastException:“无法将“Newtonsoft.Json.Linq.JValue”类型的对象强制转换为“System.Guid”类型。” 堆栈: at System.Data.SqlClient.SqlException..ctor(SerializationInfo si, StreamingContext s

反序列化包含SqlException实例的JSON字符串时出错

环境资料: -.NET核心:版本2.2 -Json:11.0.1版

结果错误: System.InvalidCastException:“无法将“Newtonsoft.Json.Linq.JValue”类型的对象强制转换为“System.Guid”类型。”

堆栈:

 at System.Data.SqlClient.SqlException..ctor(SerializationInfo si, StreamingContext sc)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
下面是重现我的问题的测试:

[Fact(DisplayName = nameof(TestShitSingleSqlEx2))]
public async Task TestErrorSingleSqlEx2()
{
    string json = @"{
    ""$type"": ""System.Data.SqlClient.SqlException, System.Data.SqlClient"",
    ""ClassName"": ""System.Data.SqlClient.SqlException"",
    ""Message"": ""A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)"",
    ""Data"": {
                ""$type"": ""System.Collections.ListDictionaryInternal, System.Private.CoreLib"",
    ""HelpLink.ProdName"": ""Microsoft SQL Server"",
    ""HelpLink.EvtSrc"": ""MSSQLServer"",
    ""HelpLink.EvtID"": ""0"",
    ""HelpLink.BaseHelpUrl"": ""http://go.microsoft.com/fwlink"",
    ""HelpLink.LinkId"": ""20476"",
    ""SqlError 1"": ""System.Data.SqlClient.SqlError: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)""
    },
    ""InnerException"": null,
    ""HelpURL"": null,
    ""StackTraceString"": ""   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\\n   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\\n   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\\n   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\\n   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\\n   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\\n   at System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken cancellationToken)\\n--- End of stack trace from previous location where exception was thrown ---\\n   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)\\n   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)\\n   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)\\n   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)\\n   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)\\n   at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.MoveNextCore(CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\Select.cs:line 106\\n   at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\AsyncIterator.cs:line 98\\n   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)\\n   at System.Collections.Generic.AsyncEnumerableHelpers.ToArrayWithLength[T](IAsyncEnumerable`1 source, CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\AsyncEnumerableHelpers.cs:line 48\\n   at System.Collections.Generic.AsyncEnumerableHelpers.ToArray[T](IAsyncEnumerable`1 source, CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\AsyncEnumerableHelpers.cs:line 16\\n   at XXXXXX.Manufacturing.Sublot.EntityFramework.Repositories.SublotRepository.LoadDataModelAsync(IEnumerable`1 ids) in /src/Sublot/Sublot.EntityFramework/Repositories/SublotRepository.cs:line 28\\n   at XXXXXX.Manufacturing.EntityFramework.Repository.DbMultiMapRepository`3.OnGetAsync(IEnumerable`1 ids)\\n   at XXXXXX.Manufacturing.Repository.MultiRepository`1.GetAsync(String id)\\n   at XXXXXX.Manufacturing.Sublot.Cqrs.Handlers.SublotHandler.Handle(MoveSublotCommand command) in /src/Sublot/Sublot.Cqrs.Handlers/SublotHandler.cs:line 193\\n   at Rebus.Pipeline.Receive.HandlerInvoker`1.Invoke()\\n   at Rebus.Pipeline.Receive.DispatchIncomingMessageStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Sagas.LoadSagaDataStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Sagas.Exclusive.NewEnforceExclusiveSagaAccessIncomingStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Pipeline.Receive.ActivateHandlersStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Pipeline.Receive.HandleRoutingSlipsStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Retry.Simple.FailedMessageWrapperStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Pipeline.Receive.HandleDeferredMessagesStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Retry.FailFast.FailFastStep.Process(IncomingStepContext context, Func`1 next)\\n   at Rebus.Retry.Simple.SimpleRetryStrategyStep.DispatchWithTrackerIdentifier(Func`1 next, String identifierToTrackMessageBy, ITransactionContext transactionContext, String messageId, String secondLevelMessageId)"",
    ""RemoteStackTraceString"": null,
    ""RemoteStackIndex"": 0,
    ""ExceptionMethod"": null,
    ""HResult"": -2146232060,
    ""Source"": ""Core .Net SqlClient Data Provider"",
    ""WatsonBuckets"": null,
    ""Errors"": null,
    ""ClientConnectionId"": ""00000000-0000-0000-0000-000000000000""
    }";

    var settings = new JsonSerializerSettings()
    {
        TypeNameHandling = TypeNameHandling.All,
    }; ;

    var cmd = JsonConvert.DeserializeObject<System.Data.SqlClient.SqlException>(json, settings);
}
[事实(DisplayName=nameof(TestShitSingleSqlEx2))]
公共异步任务TestErrorSingleSqlEx2()
{
字符串json=@”{
“$type”“:”System.Data.SqlClient.SqlException,System.Data.SqlClient”“,
“ClassName”“:”“System.Data.SqlClient.SqlException”“,
“消息”“:”“建立到SQL Server的连接时发生与网络相关或特定于实例的错误。找不到或无法访问该服务器。请验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。(提供程序:TCP提供程序,错误:40-无法打开到SQL Server的连接)”",
“数据”:{
“$type”:“System.Collections.ListDictionaryInternal,System.Private.CoreLib”,
“HelpLink.ProdName”“:”“Microsoft SQL Server”“,
“HelpLink.EvtSrc”“:”“MSSQLServer”“,
“HelpLink.EvtID:”“0”“,
“HelpLink.BaseHelpUrl:”http://go.microsoft.com/fwlink"",
HelpLink.LinkId:“20476”,
“SqlError 1”“:”“System.Data.SqlClient.SqlError:建立到SQL Server的连接时发生与网络相关或特定于实例的错误。找不到或无法访问该服务器。请验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。(提供程序:TCP提供程序,错误:40-无法打开到SQL Server的连接)”
},
“InnerException”:null,
“帮助URL”:null,
“StackTraceString”“:”“at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject,UInt32 WaitForMultipleObjectsStimOut,Boolean allowCreate,Boolean OnlyOnEckConnection,DbConnectionOptions userOptions,DbConnectionInternal&connection)\\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject、TaskCompletionSource`1重试、DbConnectionOptions用户选项、DbConnectionInternal和connection)\\n位于System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection,TaskCompletionSource`1重试,DbConnectionOptions用户选项,DbConnectionInternal oldConnection,DbConnectionInternal&connection)\\n位于System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection,DbConnectionFactory connectionFactory,TaskCompletionSource`1重试,DbConnectionOptions用户选项)\\n位于System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection,DbConnectionFactory connectionFactory,TaskCompletionSource`1重试,DbConnectionOptions用户选项)\\n位于System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1重试)\\n位于System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken CancellationToken)\\n--从引发异常的上一个位置开始的堆栈结束跟踪---\\n位于Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected,CancellationToken CancellationToken)\\n位于Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken CancellationToken,Boolean errorsExpected)\\n位于Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext,布尔缓冲区,CancellationToken CancellationToken)\\n位于Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState状态,Func`4操作,Func`4验证成功,CancellationToken CancellationToken)\\n位于Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken CancellationToken)\\n位于System.Linq.AsyncEnumerable.SelectEnumerableAleasEnumerator`2.MoveNextCore(CancellationToken CancellationToken CancellationToken)在D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\Select.cs:System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken CancellationToken)处的第106\\n行在D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\AsyncIterator.cs:Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken CancellationToken)中的第98\\n行\\n位于System.Collections.Generic.AsyncEnumerableHelpers.ToArrayWithLength[T](IAsyncEnumerable`1 source,CancellationToken CancellationToken)中的D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\source\\\\\System.Interactive.Async\\\\\AsyncEnumerableHelpers.cs:System.Collections.Generic.AsyncEnumerableHelpers.ToArray[T]第48行(IAsyncEnumerable`1 source,CancellationToken CancellationToken)位于D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\source\\\\System.Interactive.Async\\\\\AsyncEnumerableholpers.cs:XXXXXX.Manufacturing.Sublot.EntityFramework.Repositories.SublotRepository.LoadDataModelAsync(IEnumerable`1 ID)的第16行\\)在/src/Sublot/Sublot.EntityFramework/Repositories/SublotRepository.cs中:第28行\\n在XXXXXX.Manufacturing.EntityFramework.Repository.dbmultimaprository`3.OnGetAsync(IEnumerable`1 id)\\n在XXXXXX.Manufacturing.Repository.MultiRepository`1.GetAsync(字符串id)\\n在XXXXXX.Manufacturing.Sublot.Cqrs.handler.SublotHandler(MoveSublotCommand)在/src/Sublot/Sublot.Cqrs.Handlers/SublotHandler.cs中:Rebus.Pipeline.Receive.HandlerInvoker`1.Invoke()\\n在Rebus.Pipeline.Receive.DispatchIncomingMessageStep.Process(IncomingStepContext,Func`1 next)\\n在Rebus.Sagas.LoadSagaDataStep.Process(IncomingStepContext,Func`1 next)\\n在Rebus.Sagas.Exclusive.newEnforceExclusiesAgaaccessIncomingStep.Process(传入
private SqlException(SerializationInfo si, StreamingContext sc) : base(si, sc)
        {
            HResult = SqlExceptionHResult;
            foreach (SerializationEntry siEntry in si)
            {
                if ("ClientConnectionId" == siEntry.Name)
                {
                    _clientConnectionId = (Guid)siEntry.Value;
                    break;
                }
            }
        }