如何使用RestSharp在Body中提交JSON数据以发布到API?

时间:2018-05-14 18:16:13

标签: c# restsharp

我无法使用restsharp将此JSON数据发布到正文中:

{
  "odds-type":"DECIMAL",
  "exchange-type":"back-lay",
  "offers":
    [{
        "runner-id":401525949430009,
        "side":"back",
        "odds": 2.4,
        "stake": 5.0
    }
]}

我已经使用更简单的帖子端点登录了:

登录时的JSON数据很简单:

{
  "username": "jblogss",
  "password": "verysecurepassword"
}

我使用的C#代码是:

    public void Login(ref RestClient WClient)
    {  
        WClient.CookieContainer = new System.Net.CookieContainer();
        var request = new RestRequest(SECURITY, Method.POST);
        request.RequestFormat = DataFormat.Json;

        AskCredentials();

        request.AddBody(new { username = UserName, password = Password }); // uses JsonSerializer

        IRestResponse response = WClient.Execute(request);                //var response = WCient.Execute(request); works well too

        Display("LOGIN", response.Content, "Pretty", "Login.JSON");

        o_Login = PostLoginObject.FromJson(response.Content);
    }  

但是对于JSON一开始,我尝试了很多东西但没有工作。有什么想法吗?

我有一个适用于此JSON数据的C#代码但不是restsharp(我想要的那个):

    public void PlaceOfferOnRunner()
    {
        try
        {
            string accessCommand = "offers";
            string responseData = string.Empty;
            HttpWebRequest request = null;
            request = WebRequest.Create("" + AccessApi.baseAddress + "" + accessCommand + "") as HttpWebRequest;
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Uri(AccessApi.apiAddress), new Cookie("session-token", Login.SessionToken));
            request.ContentType = "application/json; charset=utf-8";
            request.Accept = "application/json";
            request.Method = "POST";

            string data = "{'odds-type':'" + OddType + "','exchange-type':'" + ExchangeType + "','offers':[{'odds': '" + Odds + "'," +
                           "'stake':" + Stake + ",'side':'" + Side + "','runner-id':" + RunnerId + "}]}";

            JObject jsonData = JObject.Parse(data);
            request.ContentLength = jsonData.ToString().Length;

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(jsonData);
                streamWriter.Flush();
                streamWriter.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            responseData = reader.ReadToEnd();
            JObject parsedJson = JObject.Parse(responseData);
            OfferId = parsedJson["offers"][0]["id"].ToString();
            Console.WriteLine(parsedJson);
            AccessApi.CallDataAccessMethods("o", "Offers  to show offer status");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex.Message);
        }
        finally { AccessApi.GetParameterValues("PlaceOfferOnRunner"); }

    }

当我尝试所有事情并且失败时,我回到工具,通常立即给出一个有效的答案,这里邮递员给予restsharp代码但也失败了(我不相信邮递员也失败了......):

var client = new RestClient("https://api.matchbook.com/edge/rest        /offers");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "4969dd04-a630-4d45-       ba61-860edef63750");
request.AddHeader("Cache-Control", "no-cache");
request.AddParameter("undefined", "{\r\n  \"odds-type\":\"DECIMAL\",\r\n       \"exchange-type\":\"back-lay\",\r\n  \"offers\":\r\n    [{\r\n            \"runner-id\":401525949430009,\r\n        \"side\":\"back\",\r\n        \"odds\": 2.4,\r\n        \"stake\": 5.0\r\n    }\r\n]}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

1 个答案:

答案 0 :(得分:0)

这是一个邮差错误,即代替

request.AddParameter("undefined", "{\r\n  \"odds-type\":\"DECIMAL\",\r\n       \"exchange-type\":\"back-lay\",\r\n  \"offers\":\r\n    [{\r\n            \"runner-id\":401525949430009,\r\n        \"side\":\"back\",\r\n        \"odds\": 2.4,\r\n        \"stake\": 5.0\r\n    }\r\n]}", ParameterType.RequestBody);

您需要使用:

request.AddParameter("application/json", "{\r\n  \"odds-type\":\"DECIMAL\",\r\n       \"exchange-type\":\"back-lay\",\r\n  \"offers\":\r\n    [{\r\n            \"runner-id\":401525949430009,\r\n        \"side\":\"back\",\r\n        \"odds\": 2.4,\r\n        \"stake\": 5.0\r\n    }\r\n]}", ParameterType.RequestBody);

"未定义"不是一种选择。