使用RestSharp Post Object作为JSON,并从调用的另一侧读取它

时间:2017-11-28 21:50:30

标签: c# json post restsharp

我有一个C#REST Web API,我有一些像这样的代码向端点发出请求。我想传递的一些数据是我自己类型的对象,因为它是一个复杂的对象,我想用POST传递它。

RestClient client = new RestClient(Constants.Endpoints.serviceEndPoint)
{
    Timeout = 1000
};

string requestResource = Constants.Endpoints.apiEndPoint;
RestRequest request = new RestRequest(requestResource, Method.POST);
request.AddParameter("Authorization", $"Bearer {accessToken}", ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.AddParameter("id", id, ParameterType.UrlSegment);
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);

IRestResponse response = client.Execute(request);

另一方面,我试图用这样的代码读取对象本身

var provider = new MultipartMemoryStreamProvider();

await Request.Content.ReadAsMultipartAsync(provider);

    foreach (var content in provider.Contents)
    { 
       // what should I do here to read the content as a JSON 
       // and then transform it as the object it used to be before the call?
    }

我试图 await content.ReadAsJsonAsync< MyType>(); 但也尝试了 await content.ReadAsStringAsync(); ,但这些都没有奏效。我在客户端执行时出错了吗?或者是在阅读内容时我在另一边做什么?

1 个答案:

答案 0 :(得分:1)

而不是这一行: request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);

您应该使用.AddBody(object)方法。 所以你的代码看起来像这样:

RestRequest request = new RestRequest(requestResource, Method.POST);
//add other headers as needed
request.RequestFormat = DataFormat.Json;
request.AddBody(objectIWantToSerialize);

IRestResponse response = client.Execute(request);

在服务器上,如果您正在使用MVC / WebAPI,则可以将C#类型作为输入,ASP.NET将为您反序列化它。如果没有,您能否提供更多关于您如何接收请求的背景信息?