Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法强制转换类型为';Newtonsoft.Json.Linq.JObject';输入';System.Runtime.Serialization.ISafeSerializationData';_C#_Json_Asp.net Web Api_Json.net - Fatal编程技术网

C# 无法强制转换类型为';Newtonsoft.Json.Linq.JObject';输入';System.Runtime.Serialization.ISafeSerializationData';

C# 无法强制转换类型为';Newtonsoft.Json.Linq.JObject';输入';System.Runtime.Serialization.ISafeSerializationData';,c#,json,asp.net-web-api,json.net,C#,Json,Asp.net Web Api,Json.net,我在尝试反序列化web api调用时遇到以下异常-消息不清楚,因此我无法理解发生了什么-此强制转换在其他情况下工作,不确定这里出了什么问题: 例外情况: InnerException: System.Reflection.TargetInvocationException _HResult=-2146232828 _message=Exception has been thrown by the target of an invocation. HResult=-21462

我在尝试反序列化web api调用时遇到以下异常-消息不清楚,因此我无法理解发生了什么-此强制转换在其他情况下工作,不确定这里出了什么问题:

例外情况:

  InnerException: System.Reflection.TargetInvocationException
   _HResult=-2146232828
   _message=Exception has been thrown by the target of an invocation.
   HResult=-2146232828
   IsTransient=false
   Message=Exception has been thrown by the target of an invocation.
   Source=mscorlib
   StackTrace:
        at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
        at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
        at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
        at Newtonsoft.Json.Serialization.JsonContract.<>c__DisplayClass1.<CreateSerializationCallback>b__0(Object o, StreamingContext context)
        at Newtonsoft.Json.Serialization.JsonContract.InvokeOnDeserialized(Object o, StreamingContext context)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.OnDeserialized(JsonReader reader, JsonContract contract, Object value)
        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.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract 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.CreateValueInternal(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.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
        at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
        at System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
        at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
     --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
        at System.Net.Http.HttpContentExtensions.<ReadAsAsyncCore>d__0`1.MoveNext()
   InnerException: System.InvalidCastException
        _HResult=-2147467262
        _message=Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Runtime.Serialization.ISafeSerializationData'.
        HResult=-2147467262
        IsTransient=false
        Message=Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Runtime.Serialization.ISafeSerializationData'.
        Source=mscorlib
        StackTrace:
             at System.Runtime.Serialization.SafeSerializationManager.CompleteDeserialization(Object deserializedObject)
             at System.Exception.OnDeserialized(StreamingContext context)
        InnerException: 
InnerException:System.Reflection.targetingException
_HResult=-2146232828
_message=调用目标已引发异常。
HResult=-2146232828
IsTransient=false
Message=调用目标已引发异常。
Source=mscorlib
堆栈跟踪:
位于System.RuntimeMethodHandle.InvokeMethod(对象目标、对象[]参数、签名符号、布尔构造函数)
位于System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(对象obj,对象[]参数,对象[]参数)
在System.Reflection.RuntimeMethodInfo.Invoke(对象obj、BindingFlags invokeAttr、绑定器绑定器、对象[]参数、CultureInfo区域性)
在System.Reflection.MethodBase.Invoke(对象obj,对象[]参数)处
位于Newtonsoft.Json.Serialization.JsonContract.c__DisplayClass1.b__0(对象o,StreamingContext上下文)
位于Newtonsoft.Json.Serialization.JsonContract.InvokeOnDeserialized(对象o,StreamingContext上下文)
在Newtonsoft.Json.Serialization.JsonSerializerInternalReader.OnDeserialized(JsonReader、JsonContract契约、对象值)
位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateSerializable(JsonReader阅读器,JsonISerializableContract契约,JsonProperty成员,字符串id)
位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader阅读器,类型objectType,JsonContract契约,JsonProperty成员,JsonContainerContract容器契约,JsonProperty容器成员,对象existingValue)
位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader阅读器,类型objectType,JsonContract合同,JsonProperty成员,JsonContainerContract容器合同,JsonProperty容器成员,对象existingValue)
位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty属性、JsonConverter属性转换程序、JsonContainerContract容器合同、JsonProperty容器属性、JsonReader阅读器、对象目标)
位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(对象newObject、JsonReader、JSONObject合同、JsonProperty成员、字符串id)
位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader阅读器,类型objectType,JsonContract契约,JsonProperty成员,JsonContainerContract容器契约,JsonProperty容器成员,对象existingValue)
位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader阅读器,类型objectType,JsonContract合同,JsonProperty成员,JsonContainerContract容器合同,JsonProperty容器成员,对象existingValue)
在Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader阅读器,类型objectType,Boolean checkAdditionalContent)
位于Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader,类型objectType)
在Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader阅读器,类型objectType)
位于System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(类型类型、流readStream、编码有效编码、IFormatterLogger格式记录器)
位于System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStream(类型类型、流readStream、编码有效编码、IFormatterLogger formatterLogger)
位于System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(类型类型、流readStream、HttpContent内容、IFormatterLogger格式记录器)
位于System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStreamAsync(类型类型、流readStream、HttpContent内容、IFormatterLogger格式记录器)
---来自引发异常的上一个位置的堆栈结束跟踪---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()中
在System.Net.Http.HttpContentExtensions.d_u0`1.MoveNext()中
InnerException:System.InvalidCastException
_HResult=-2147467262
_message=无法将“Newtonsoft.Json.Linq.JObject”类型的对象强制转换为“System.Runtime.Serialization.ISafeSerializationData”类型。
HResult=-2147467262
IsTransient=false
Message=无法将“Newtonsoft.Json.Linq.JObject”类型的对象强制转换为“System.Runtime.Serialization.ISafeSerializationData”类型。
Source=mscorlib
堆栈跟踪:
在System.Runtime.Serialization.SafeSerializationManager.CompleteDeserialization(对象反序列化对象)
在System.Exception.OnDeserialized处(StreamingContext上下文)
内部异常:
我的代码:

public SensoriaApiResult<T> PostSensoriaApiResult(object body)
    {
        HttpClient client = SetupClient();

        HttpResponseMessage response;
        response = client.PostAsJsonAsync(url, body).Result;

        SensoriaApiResult<T> result = response.Content.ReadAsAsync<SensoriaApiResult<T>>().Result;
        return result;
    }
public sensoriaapirect postssensoriaapirect(对象体)
{
HttpClient=SetupClient();
HttpResponseMessage响应;
response=client.PostAsJsonAsync(url,body.Result);
sensoriaapireult=response.Content.ReadAsAsync().result;
返回结果;
}
Json返回:

{"StatusCode":500,"APIResult":null,"HttpError":{"Message":"Sensoria API internal error","SensoriaApiErrorCode":983041},"Exception":{"ClassName":"System.Data.Entity.Infrastructure.DbUpdateException","Message":"An error occurred while updating the entries. See the inner exception for details.","Data":{},"InnerException":{"ClassName":"System.Data.Entity.Core.UpdateException","Message":"An error occurred while updating the entries. See the inner exception for details.","Data":{},"InnerException":{"Errors":[{"source":".Net SqlClient Data Provider","number":547,"state":0,"errorClass":16,"server":".","message":"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_UserBase.ClosetItems_Catalog.Products\". The conflict occurred in database \"Sensoria.Knowledge.Database\", table \"dbo.Catalog.Products\", column 'ProductId'.","procedure":"","lineNumber":1,"win32ErrorCode":0},{"source":".Net SqlClient Data Provider","number":3621,"state":0,"errorClass":0,"server":".","message":"The statement has been terminated.","procedure":"","lineNumber":1,"win32ErrorCode":0}],"ClientConnectionId":"7b976c29-59ff-491c-a3aa-01750e17cb36","ClassName":"System.Data.SqlClient.SqlException","Message":"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_UserBase.ClosetItems_Catalog.Products\". The conflict occurred in database \"Sensoria.Knowledge.Database\", table \"dbo.Catalog.Products\", column 'ProductId'.\r\nThe statement has been terminated.","Data":{"HelpLink.ProdName":"Microsoft SQL Server","HelpLink.ProdVer":"11.00.3128","HelpLink.EvtSrc":"MSSQLServer","HelpLink.EvtID":"547","HelpLink.BaseHelpUrl":"http://go.microsoft.com/fwlink","HelpLink.LinkId":"20476"},"InnerException":null,"HelpURL":null,"StackTraceString":"   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n   at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()\r\n   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)\r\n   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)\r\n   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":"8\nOnError\nSystem.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Data.SqlClient.SqlConnection\nVoid OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action])","HResult":-2146232060,"Source":".Net SqlClient Data Provider","WatsonBuckets":null},"HelpURL":null,"StackTraceString":"   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction, Boolean throwOnClosedConnection)\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(Boolean throwOnClosedConnection)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__33()\r\n   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass28.<SaveChanges>b__25()\r\n   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)\r\n   at System.Data.Entity.Internal.InternalContext.SaveChanges()","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":"8\nUpdate\nEntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator\nInt32 Update()","HResult":-2146233087,"Source":"EntityFramework","WatsonBuckets":null},"HelpURL":null,"StackTraceString":"   at Sensoria.Models.ShoeClosetModel.CreateClosetModelForUser(Int32 userId, ShoeClosetItem newClosetItem) in c:\\Users\\maurgi\\Source\\Hg\\sensoria-main\\Source\\Web\\Sensoria.Models\\ShoeClosetModel.cs:line 225\r\n   at Sensoria.Models.ShoeClosetModel.CreateClosetItem(Int32 userID, ShoeClosetItem newClosetItem) in c:\\Users\\maurgi\\Source\\Hg\\sensoria-main\\Source\\Web\\Sensoria.Models\\ShoeClosetModel.cs:line 76\r\n   at Sensoria.Api.Controllers.ShoeClosetController.AddNewShoe(Int32 userId, ShoeClosetItem sItem) in c:\\Users\\maurgi\\Source\\Hg\\sensoria-main\\Source\\Web\\Sensoria.Api\\Controllers\\ShoeClosetController.cs:line 79","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":"8\nCreateClosetModelForUser\nSensoria.Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\nSensoria.Models.ShoeClosetModel\nSensoria.Models.ShoeClosetModel CreateClosetModelForUser(Int32, Sensoria.Api.Core.Models.ShoeClosetItem)","HResult":-2146233087,"Source":"Sensoria.Models","WatsonBuckets":null,"SafeSerializationManager":{"m_serializedStates":[{"<InvolvesIndependentAssociations>k__BackingField":false}]},"CLR_SafeSerializationManager_RealType":"System.Data.Entity.Infrastructure.DbUpdateException, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"},"ModelState":null}
{“StatusCode”:500,“APIResult”:null,“HttpError”:{“Message”:“Sensoria API内部错误”,“SensoriaApiErrorCode”:983041},“Exception”:{“ClassName”:“System.Data.Entity.Infrastructure.DbUpdateException”,“Message”:“更新条目时出错。有关详细信息,请参阅内部异常”。,“Data”:{},“InnerException”:{“ClassName”:“System.Data.Entity.Core.update
public class SensoriaApiResult<T>
{
    /// <summary>
    /// The 
    /// </summary>
    [DataMember]
    public HttpStatusCode StatusCode;
    [DataMember]
    public T APIResult;
    [DataMember]
    public HttpError HttpError;
    [DataMember]
    public Exception Exception;
    [DataMember]
    public ModelStateDictionary ModelState;

    ...
string myJson = JsonConvert.SerializeObject(myObject).Replace("\"SafeSerializationManager\":", "\"_SafeSerializationManager\":");