![](/img/trans.png)
[英]RestSharp: Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`
[英]RestSharp unable to cast object when awaiting for response
使用RestSharp我正在构建一个API,在给定数据类型/对象的情况下执行CRUD操作。
我的CrudAbstract
类是通用的,具有以下内容:
public virtual async Task<keyType> Post(dto item)
{
try
{
var request = await _client.GetRequestAsync(_path);
request.Method = RestSharp.Method.POST;
request.AddJsonBody(item);
var result = await _client.ExecuteRequestAsync<keyType>(request);
return result;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
throw new Exception("Was not able to process crud post operation.");
}
我的WebClient
类具有以下内容:
Entities = new CrudAbstract<DtoEntity, int>("/entities", this); // in constructor
// So the keyType from definition above is int (Int32)
这个类中的post方法是
public async Task<T> ExecuteRequestAsync<T>(IRestRequest request)
{
try
{
var response = await GetClient().ExecuteTaskAsync<T>(request);
// Exception occurs here. The above statement is unable to finish.
var data = response.Data;
return data;
}
catch (Exception e)
{
// Log exception
}
throw new Exception("Was not able to process restclient execute async method.");
}
我的Api EntitiesController
具有以下内容:
public int Post(DtoEntity value)
{
using (var db = // some database...)
{
try
{
// Upsert object into database here
//... value.Id no longer null at this point
/*
The problem occurs here. I only want to return the ID of the object
(value.Id). I do not want to return the whole object (value)
*/
return value.Id;
}
catch (Exception e)
{
// Log exception
}
}
throw new Exception("Was not able to process entities post method.");
}
我得到的例外是:
无法将类型为'System.Int64'的对象强制转换为'System.Collections.Generic.IDictionary`2 [System.String,System.Object]'。
这基本上是说它无法将对象int
(我在带有value.Id
的帖子中value.Id
)转换为DtoEntity
对象(这是执行CRUD操作的实际对象)。
我究竟做错了什么?
我已将typeof
和.getType()
放在每个keyType
, T
和value.Id
,并且所有这些都是Int32
。 是否在RestSharp库中出现问题? 在什么阶段有一个int
转换为DtoEntity
中的DtoEntity
:
var response = await GetClient().ExecuteTaskAsync<T>(request);
注意:当我将控制器中post方法的返回类型更改为DtoEntity
并更改value.Id
只是value
它可以工作。 收到response
, response.Data
是DtoEntity
对象。
我相信你在RestSharp中发现了一个错误。 RestSharp在内部使用一个名为SimpleJson的JSON解析器(从Facebook .NET SDK中借用)。 看来这个解析器正确地将响应体反序列化为一个数字(因为JSON是无类型的,它使用Int64是安全的),但RestSharp的JsonDeserializer类试图将此结果转换为此方法第一行中的IDictionary
:
private object FindRoot(string content)
{
var data = (IDictionary<string, object>)SimpleJson.DeserializeObject(content);
if (RootElement.HasValue() && data.ContainsKey(RootElement))
{
return data[RootElement];
}
return data;
}
我认为你的选择是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.