我有一个声明如下的WCF服务:
[OperationContract, XmlSerializerFormat]
[WebInvoke(UriTemplate = "ProessUpload",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Xml)]
void ProcessUpload(ProductConfig stream);
我试图使用WebClient调用此服务,但服务器总是返回400(BadRequest)响应。然而,如果我使用HttpWebRequest,则WCF会消耗我的帖子并正确响应200。我还能够成功地使用Fiddler构建请求来调用WCF服务。
WebClient 代码
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 代码
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();
正在发送的XML
var data2 = @"<Product><Sku>3327</Sku><NameProduct</Name><Category>Bumper</Category><Brand Id='3'><Collection>14</Collection></Brand></Product>";
为什么 HttpWebRequest 可以工作而 WebClient 不行呢?我在 Fiddler 中看不出发送的头部有什么实质性的区别。