我有一个 WCF 服务声明如下:
[OperationContract, XmlSerializerFormat]
[WebInvoke(UriTemplate = "ProessUpload",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Xml)]
void ProcessUpload(ProductConfig stream);
我正在尝试使用 WebClient 调用此服务,但我总是从服务器收到响应 400 (BadRequest)。但是,如果我使用 HttpWebRequest,WCF 会消耗我的帖子并正确响应 200。我还能够使用 Fiddler 成功构造一个请求来调用 WCF 服务。
Web客户端代码
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 发送的标头有真正的区别。