【问题标题】:How to pass JSON string to another api using RESTSharp?如何使用 RESTSharp 将 JSON 字符串传递给另一个 api?
【发布时间】:2016-10-03 04:06:27
【问题描述】:

问题说明:

资源 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()

提前致谢。

【问题讨论】:

    标签: asp.net-mvc rest asp.net-web-api json.net restsharp


    【解决方案1】:

    对于使用request.AddUrlSegment("username", "Admin"),您应该正确定义您的网址模板:var request = new RestRequest("api/employee/{username} ", Method.POST);

    你也应该设置Content-Type

    request.AddHeader("Content-Type", @"application/json");
    

    在添加 Body

    之前

    【讨论】:

    • 谢谢您的回复。我发现我的代码没有问题。它工作正常。 :)
    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 2021-09-25
    相关资源
    最近更新 更多