在RestSharp中使用POST方法

0 c# api restsharp

我想使用 RestSharp 将数据发布到我的 API:

创建.php

我的结构是这样的:

读取.php

在 PostMan 中,我使用正文选项和原始输入,如下所示:

{
    "story_code" : "Amazing Pillow 2.0",
    "master_code" : "199",
    "created" : "2018-06-01 00:35:07"
}
Run Code Online (Sandbox Code Playgroud)

邮差

它有效。在 RestSharp 中,我使用了这段代码,但它返回了错误请求和消息:“无法创建产品。数据不完整。”

var client = new RestClient("http://api.dastanito.ir");
var request = new RestRequest("/storiesmaster/creat.php", Method.POST);

request.AddParameter("story_code", "value");
request.AddParameter("master_code", "value2");

IRestResponse response = client.Execute(request);
var content = response.Content;
Run Code Online (Sandbox Code Playgroud)

我什至使用了 AddQueryParameter 但又是错误的请求。

我应该使用什么功能?

ste*_*351 5

相反,.AddParameter您可以使用AddJsonBody类似于邮递员发送的内容来获取您已经知道工作正常的内容。

例如下面的代码可以工作:

var client = new RestClient("http://api.dastanito.ir");
var request = new RestRequest("/storiesmaster/creat.php", Method.POST);

request.AddJsonBody(new
{
    story_code = "value",
    master_code = "value2"
});

IRestResponse response = client.Execute(request);
var content = response.Content; // {"message":" created."}
Run Code Online (Sandbox Code Playgroud)

如果您使用 Fiddler 检查传出消息,它看起来像这样:

{"story_code":"value","master_code":"value2"}

而您使用的消息AddParameter如下所示:

故事代码=值&主代码=值2