如何使用RESTSharp将JSON字符串传递给另一个api



问题说明:

资源URI: address/index.php?r=api/employee

请求报头:Content- Type: application/json

HTTP方法:POST

请求体:{ "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}

上述参数应以JSON字符串形式作为一行HTTP POST传递给系统。

我正在尝试使用RESTSharp解决这个问题。但是我有一些问题,就像执行请求后,我的代码返回一个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");

添加Body

相关内容

  • 没有找到相关文章