1

How do I make a GET query with request body using RestSharp (I'm using RestSharp v. 106.6.10 with .NET Core 2.2). I can do it using WebClient/Postman etc. no problem.

Here's the code failing with {["A non-empty request body is required."]}.

var client = new RestClient("BaseUri");
var request = new RestRequest("URL", Method.GET);
request.AddJsonBody(Body); 
client.Execute(request); // {["A non-empty request body is required."]}

This represents a valid use case, pity if it's not supported.

Update: The motivation for having GET requests with body is to avail of get requests having complex parameters, which can't be nicely encoded into a query string. I know people serialize their jsons an put them into a querystrings but I'd rather put it into a request body, considering it's a permissible usage after all.

Antonín Procházka
  • 1,388
  • 8
  • 16
JsCoder
  • 117
  • 1
  • 9
  • 1
    it might be technically permitted, but - it isn't exactly normal usage; it doesn't amaze me that some tools don't love it; but : have you tried with `HttpClient` ? – Marc Gravell Jul 30 '19 at 10:25
  • take a look at this one https://stackoverflow.com/questions/5095692/how-to-add-text-to-request-body-in-restsharp – misticos Jul 30 '19 at 10:37
  • @IvMisticos - doesn't work, getting the same error. – JsCoder Jul 30 '19 at 11:05
  • 1
    @MarcGravell I've tried WebClient and didn't seem to like it neither, saying explicitly that GETs aren't allowed having bodies. – JsCoder Jul 30 '19 at 11:06
  • 1
    @MarcGravell ProtocolViolationException: Cannot send a content-body with this verb-type. is what I'm getting from WebClient. – JsCoder Jul 30 '19 at 11:27

2 Answers2

2

From my experience AddJsonBody is completely broken (had a multiple times when it wasn't serialize my model just pasting in Body something like MyProject.Models.MyModel or even left body empty). So I use following:

var client = new RestClient("BaseUri");
var request = new RestRequest("URL", Method.GET);
request.AddHeader("Content-Type", "application/json");
string serializedBody = Newtonsoft.Json.JsonConvert.SerializeObject(Body);
request.AddParameter("application/json; charset=utf-8", serializedBody, ParameterType.RequestBody);
client.Execute(request);

UPDATE sorry i wasn't patient when reading you question. Answer is provided for RestSharp not PostSharp

Lemm
  • 196
  • 1
  • 9
  • Tried it as it, got: "StatusCode: UnsupportedMediaType, Content-Type: , Content-Length: 0)" – JsCoder Jul 30 '19 at 12:11
  • After adding: request.AddHeader("Content-Type", "application/json; charset=utf-8"); I start getting my original BadRequest. – JsCoder Jul 30 '19 at 12:13
  • Possibly your server not allowing calls without `Content-Length` specified. Try to add `request.AddHeader("Content-Length", $"{System.Text.Encoding.ASCII.GetByteCount(serializedBody)}");` – Lemm Jul 30 '19 at 13:11
  • It's not the length, it's Content-Type what it's unhappy about. My guess it RestSharp could well use WebClient/HttpClient in which case it's predefined to fail. – JsCoder Jul 30 '19 at 14:39
  • RestSharp seems correct - this is not about PostSharp. I've suggested an edit of the question - waiting for peer review. – Antonín Procházka Aug 05 '19 at 07:49
0

I solved it by using reflection, to trick WebRequest that it is legal to send a body with a GET request.

1.Create Model for body parameters,

public class SampleBodyModel
{
    public String name{ get; set; }
    public String password{ get; set; }
}
  1. Initialize the request.

    SampleBodyModel sampleRequest = new SampleBodyModel
    {
          name= "name",
          password= "password"
    };
    
    //initialize the API call
    var request = WebRequest.Create("API_END_POINT");
    request.ContentType = "application/json";
    request.Method = "GET";
    var myHttpWebRequest = (HttpWebRequest)request;
    
    // ------- Add these two lines if your using JWT token -------
    myHttpWebRequest.PreAuthenticate = true;
    myHttpWebRequest.Headers.Add("Authorization", "Bearer " + "TOKEN");
    // -----------------------------------------------------------
    
    var type = myHttpWebRequest.GetType();
    var currentMethod = type.GetProperty("CurrentMethod", 
            BindingFlags.NonPublic | BindingFlags.Instance).GetValue(myHttpWebRequest);
    var methodType = currentMethod.GetType();
    methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | 
             BindingFlags.Instance).SetValue(currentMethod, false);
    
    //Add the Request body
    using (var streamWriter = new 
          StreamWriter(myHttpWebRequest.GetRequestStream()))
    {
    
         streamWriter.Write(Newtonsoft.Json.JsonConvert.SerializeObject(sampleRequest));
    }
    var response = (HttpWebResponse)myHttpWebRequest.GetResponse();
    var responseStream = response.GetResponseStream();
    
    var myStreamReader = new StreamReader(responseStream, Encoding.Default);
    var json = myStreamReader.ReadToEnd();
    
    responseStream.Close();
    response.Close();
    
shalitha senanayaka
  • 1,905
  • 20
  • 37