views:

2828

answers:

2

Hi, I have a WCF Service declared as follows:

[OperationContract, XmlSerializerFormat]
[WebInvoke(UriTemplate = "ProessUpload",
   BodyStyle = WebMessageBodyStyle.Bare,
   RequestFormat = WebMessageFormat.Xml)]
void ProcessUpload(ProductConfig stream);

I am trying to call this service using WebClient but I am always getting a response 400 (BadRequest) from the server. However if I use HttpWebRequest the WCF consumes my post and correctly responds with 200. I am also able to successfully construct a request using Fiddler to call the WCF Service.

WebClient Code

WebClient webClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/xml");//; charset=utf-8
try
{
  string result = webClient.UploadString("http://jeff-laptop/SalesAssist.ImageService/Process", "POST", data2);
}
  catch (Exception ex)
{
  var e = ex.InnerException;
}

HttpWebRequest code

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://jeff-laptop/SalesAssist.ImageService/Process");
request.ContentType = "application/xml";
request.Method = "POST";
request.KeepAlive = true;

using (Stream requestStream = request.GetRequestStream())
{
  var bytes = Encoding.UTF8.GetBytes(data2);
  requestStream.Write(bytes, 0, bytes.Length);
  requestStream.Close();
}

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

The XML that is being sent

var data2 = @"<Product><Sku>3327</Sku><NameProduct</Name><Category>Bumper</Category><Brand Id='3'><Collection>14</Collection></Brand></Product>";

Why is that HttpWebRequest works and WebClient doesn't? I can't see a real difference in the sent headers via Fiddler.

+2  A: 

Try setting the Encoding property on the WebClient before you send the string. Since you aren't specifying it I suspect it defaults to ASCII. Quoting from the UploadString reference page.

Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding property. This method blocks while the string is transmitted. To send a string and continue executing while waiting for the server's response, use one of the UploadStringAsync methods.

 webClient.Encoding = Encoding.UTF8;
tvanfosson