Restsharp- Method.POST不起作用

时间:2014-12-25 19:18:14

标签: asp.net-web-api restsharp

我根据RestSharp.org文档尝试了所有可能的方案,但没有运气!

我这里有ASP.Net Web API是POST资源

[Route("/api/saveperson/{name}/{fathername}")]    
public void Post([FromBody]CustomObject customObject, string name, string fatherName)
{
      //customObject is null
}

RestSharp请求:

public void SomeAPIRequest()
{
 var baseUrl = "someurl from config";
var client = new RestClient(baseUrl);
var request = new RestRequest("/api/saverperson/{name}/{fathername}",Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(myObject);  //This object is perfectly serialized in json
request.AddParameter("name","Gaurav",ParameterType.UrlSegment);
request.AddParameter("fathername","Lt. Sh. Ramkrishan",ParameterType.UrlSegment);

var response= client.Execute(request);

}

使用上面的代码在Body中发布的参数始终为null。

当我进行以下调用时,在Body中发布的参数具有值但其他值为空

public void SomeAPIRequest()
{
 var baseUrl = "someurl from config";
var client = new RestClient(baseUrl);
var request = new RestRequest("/api/saverperson/{name}/{fathername}",Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(myObject);  //This object is perfectly serialized in json
request.AddUrlSegment("name","Gaurav");
request.AddUrlSegment("fathername","Lt. Sh. Ramkrishan");

var response= client.Execute(request);

}

欢迎任何帮助!

1 个答案:

答案 0 :(得分:9)

我找到了解决方案。回答我自己的问题,那些面临类似问题的人可以找到解决方案。

只需要执行以下请求:

request.AddParameter("Application/Json", myObject, ParameterType.RequestBody);

以下是完整的代码段:

public void SomeAPIRequest()
{
   var baseUrl = "someurl from config";
   var client = new RestClient(baseUrl);
   var request = new RestRequest("/api/saverperson/{name}/{fathername}",Method.POST);
   request.RequestFormat = DataFormat.Json;
   request.AddParameter("Application/Json", myObject, ParameterType.RequestBody);
   request.AddUrlSegment("name","Gaurav");
   request.AddUrlSegment("fathername","Lt. Sh. Ramkrishan");

   var response= client.Execute(request);

}

以上代码解决了我的问题。