如何使用 RESTSharp 将 JSON 字符串传递给另一个 api?
How to pass JSON string to another api using RESTSharp?
问题说明:
Resource URI : address/index.php?r=api/employee
Request Header : Content- Type: application/json
HTTP Method: POST
Request Body: { "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
以上参数应作为 JSON 字符串中的一行 HTTP POST 传递给系统。
我正在尝试使用 RESTSharp
解决这个问题。但是我遇到了一些问题,比如在执行请求后我的代码 return 一个 Null 响应,我不确定我的 JSON 字符串是否正确传递。
这是我的代码:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", @"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
我的代码有问题吗??
我有点困惑
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
基本上我想知道如何利用AdduUrlSegment()
和AddParameter()
。
提前致谢。
要使用 request.AddUrlSegment("username", "Admin")
,您应该正确定义 url 模板:var request = new RestRequest("api/employee/{username} ", Method.POST);
你还应该设置 Content-Type
request.AddHeader("Content-Type", @"application/json");
在添加 正文之前
问题说明:
Resource URI :
address/index.php?r=api/employee
Request Header :
Content- Type: application/json
HTTP Method:
POST
Request Body:
{ "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
以上参数应作为 JSON 字符串中的一行 HTTP POST 传递给系统。
我正在尝试使用 RESTSharp
解决这个问题。但是我遇到了一些问题,比如在执行请求后我的代码 return 一个 Null 响应,我不确定我的 JSON 字符串是否正确传递。
这是我的代码:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", @"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
我的代码有问题吗??
我有点困惑
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
基本上我想知道如何利用AdduUrlSegment()
和AddParameter()
。
提前致谢。
要使用 request.AddUrlSegment("username", "Admin")
,您应该正确定义 url 模板:var request = new RestRequest("api/employee/{username} ", Method.POST);
你还应该设置 Content-Type
request.AddHeader("Content-Type", @"application/json");
在添加 正文之前