当前位置 : 主页 > 网络编程 > ASP >

asp.net-web-api – Restsharp- Method.POST不能正常工作

来源:互联网 收集:自由互联 发布时间:2021-06-24
我根据RestSharp.org文档尝试了所有可能的场景,但没有运气! 我这里有ASP.Net Web API是POST资源 [Route("/api/saveperson/{name}/{fathername}")] public void Post([FromBody]CustomObject customObject, string name, string
我根据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);

}

任何帮助都将受到欢迎!

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

只需要执行以下请求:

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);

}

上面的代码解决了我的问题.

网友评论