-1

I need to send XML request to REST API , it is Get Request (i cannot use Post). This code is working from Postman but in C# .Net 4.8.1 framework this code is not working , i am getting error 'Cannot send a content-body with this verb-type.'

I google a lot but getting answer , lot of people have same issue.

What wrong am I doing ? Thanks. Here is Code.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://XXXX/get/getFees");
request.Headers.Add("Authorization", "Basic XXXX);

request.Headers.Add("Cookie", "JSESSIONID=XXXX");

var content = new StringContent("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n  <soap:Body>\r\n\r\n  </soap:Body>\r\n</soap:Envelope>", null, "text/plain");

request.Content = content;

var response = await client.SendAsync(request);

response.EnsureSuccessStatusCode();

Console.WriteLine(await response.Content.ReadAsStringAsync());
Lucky Star
  • 53
  • 8
  • You need to add the http header Content-Type to your request that is consistent with the type of data in the contents (body). See : https://www.geeksforgeeks.org/http-headers-content-type/?force_isolation=true – jdweng Apr 14 '23 at 10:05
  • HTTP GET does not normally take a body, it's not to spec. https://stackoverflow.com/a/983458/14868997 Why can't you use POST? – Charlieface Apr 14 '23 at 10:05
  • @jdweng , I added the Content-Type but got same error , request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); – Lucky Star Apr 15 '23 at 03:45
  • @Charlieface , It is request and reply , I am sending request XML as payload and server will send the reply based on XML payload. No update on the server side. – Lucky Star Apr 15 '23 at 03:50
  • It's exactly as it says. You cannot send a content body if you make a GET request. That is nothing to do with C#, or Postman, or the API; it is completely about **HTTP**. – Karl Knechtel Apr 15 '23 at 07:51
  • @KarlKnechtel , I think it is .Net 4.8.1 issue , Yes you can send the content body in Get Reuest and it is working in .Net Core .70. I am doing Request and Reply pattern where I send XML Payload as request and Server reply with XML payload. – Lucky Star Apr 15 '23 at 07:56
  • 1
    Listen to what people are saying. You are sending a request with a body. GET is only for requests with no body. So You need Post. It may be that Core is not reporting the error while Net 4.8.1 is reporting the error. It just happens that Core is working because it didn't report the error. – jdweng Apr 15 '23 at 14:17

1 Answers1

-1

The above code is not working with .net 4.8.1.

I copy the same code in .Net 7.0 and it is working.

So I will be writing REST API in .Net 7.0 and calling this API from .Net 4.8

Thanks.

Lucky Star
  • 53
  • 8