0

I am trying to send a GET request with a body using C#. I am able to send the request if I pass through a regular string however if I pass in a serialized object it does not work.

CallHttpGet Method

public string CallHttpGet(string url, string json)
{
    //HTTP Get request
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Method = "GET";
    request.ContentType = "application/json";
    request.Headers.Add("Authorization",authorizationKey);
    request.Headers.Add("X-ng-requestTime", requestTime);
    var type = request.GetType();
    var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request);

    var methodType = currentMethod.GetType();
    methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(json);
    }

    var response = (HttpWebResponse)request.GetResponse();
    return new StreamReader(response.GetResponseStream()).ReadToEnd();
}

Unit Test that gets a positive result

[TestMethod]
public void Test()
{
    var svc = new Service();
    var json = "{\"designationType\" : \"MUAP\"}";
    var result = svc.CallHttpGet(myUrl,json);
    Assert.IsNotNull(result);
}

Unit Test that does not get a positive result

[TestMethod]
public void Test()
{
    var svc = new Service();
    var json = new MuaDesignationListRequest
    {
        DesignationType = "MUAP"
    };
    var result = svc.CallHttpGet(myUrl,JSONConvert.SerializeObject(json));
    Assert.IsNotNull(result);
}

MuaDesignationListRequest Object

public class MuaDesignationListRequest
{
    [JsonProperty("designationType")]
    public string DesignationType { get; set; }
}
TheProgrammer
  • 1,314
  • 5
  • 22
  • 44
  • Any particular reason you're using a `GET` request with a request body? Whilst it's *technically* allowed, it's unusual, and not all servers will necessarily support it. A `POST` or `PUT` request would be a better choice. – Richard Deeming Nov 10 '21 at 17:16
  • @RichardDeeming the endpoint that I am trying to call set it up so it uses a GET instead of POST. Unfortunately I am unable to change – TheProgrammer Nov 10 '21 at 17:35

0 Answers0