0

I've got a section of code to do a call to an external webapi using WebRequest. I'm trying to update it to use RestSharp instead. What am I missing here to make the conversion? The closest question here to give any sort of idea what might be going on is found in Calling webapi method gives 404. The "answer" was a missing accepted content type. I've verified through the RestClient the types are present (and appear valid).

Common request JSON

  var statusRequest = @"
{
    ""auth"": {
        ""type"": ""basic""
    },
    ""requestId"": ""15"",
    ""method"": {
        ""name"": ""getStatus"",
        ""params"": {
            ""showAllStatus"": ""0""
        }
    }
}
";

WebRequest code

  var webRequest = WebRequest.Create("https://service.url/api/status") as HttpWebRequest;
  webRequest.Method = "POST";

  var username = "user";
  var password = "pass";
  var encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")
                                 .GetBytes(username + ":" + password));
  webRequest.Headers.Add("Authorization", "Basic " + encoded);
  
  var requestWriter = new StreamWriter(webRequest.GetRequestStream());
  
  webRequest.ContentType = "APPLICATION/JSON; CHARSET=UTF-8";
  requestWriter.Write(statusRequest);
  
  requestWriter.Close();
  
  var responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
  var responseData = responseReader.ReadToEnd();
  responseReader.Close();

Should convert to RestSharp as

  var client = new RestClient("https://service.url");
  client.Authenticator = new HttpBasicAuthenticator("user", "pass");

  var request = new RestRequest("api/status", Method.Post);
  request.RequestFormat = DataFormat.Json;
  request.AddJsonBody(statusRequest);
  
  client.BuildUri(request);

  var response = await client.GetAsync(request);

EDIT: Make the RestRequest a POST

Ron O
  • 89
  • 7

1 Answers1

0

Please read the docs.

warning in the documentation

Also, you are calling GetAsync. Even if you set the request method to Method.Post, calling GetAsync will override it.

This will work:

var request = new RestRequest("api/status")
    .AddStringBody(statusRequest, DataFormat.Json);
var response = await client.PostAsync(request);
Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83