I have a REST based WCF web-service;
The contract is:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Xml)]
string EchoWithPost(string message);
The message is:
public string EchoWithPost(string s)
{
return "ECHO with POST : You said " + s;
}
I used the web channel factory to get a response via POST and it works. I used wireshark to tap the message and I can see some important things:
1) That xml is sent
2) The Content Type
From this I have constructed the following request logic:
//5) manually post to the REST service
//Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(urlOfService + "/rest/EchoWithPOST");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "<EchoWithPost xmlns="http://tempuri.org"><message>Hello</message><EchoWithPost>";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/xml";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
However when I hit the line that says:
dataStream =
response.GetResponseStream();
I get the following error:
“The remote server returned an error : (400) Bad Request”
Could someone help me with what I need to do as I need to be able to tell people how to manually create a POST request to interact with this REST based service.
Any help much appreciated dont really see what else I can try.
I’ve made a few small changes, so I’ll just post the entire thing. Hopefully it works for you. Also, I didn’t add any deserializing, figuring you could tackle that as long as you make it past the HTTP 400 error.
A great tool to help you debug these situations is SoapUI. Just setup a “Web TestCase”, and you can create your own POST requests and monitor the data that’s going back and forth.
-Vito
Interface:
Service:
Client:
web.config: