I have a (legacy) method in my codebase which generates and returns a ready-to-send HTTP POST message as a System.Net.HttpWebRequest object:
public HttpWebRequest GetHttpWebRequest(string body, string url, string contentType)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
// (More setup stuff here...)
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(body);
}
return request;
}
I'd like to write a unit test which verifies that the HttpWebRequest
instance returned by this method actually does have the message body text that was passed in to the method in the body
parameter.
Question: How can I get the body text of an HttpWebRequest
object (without ever actually sending the HTTP request)?
Stuff I've tried so far:
new StreamReader(myHttpWebRequest.GetRequestStream()).ReadToEnd()
- Fails at runtime withArgumentException: Stream was not readable.
- The HttpWebRequest class doesn't seem to have any property that would allow getting/reading the HTTP message body such as
Body
,Message
,Text
, etc.
I would write a http listener and make real http requests.
Here is a sample server using WCF + the client code. Just call
await TestClient.Test();
(You can also test the server with a browser likehttp://localhost:8088/TestServer/Dummy
)