WCF Post/WebRequest 工作 - WebClient 不

标签 wcf httpwebrequest webclient

我有一个 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 = 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 发送的 header 有什么真正的区别。

最佳答案

尝试设置 Encoding在发送字符串之前 WebClient 上的属性。由于您没有指定它,我怀疑它默认为 ASCII。引用自 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;

关于WCF Post/WebRequest 工作 - WebClient 不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/645902/

相关文章:

通过 netTcp 的 WCF 自定义安全性

c# - Silverlight 4 最快的 WCF 绑定(bind)

ssl - HttpWebRequest Server Unavailable 503问题

C# HttpWebRequest.GetResponse - StatusCode 用法是如何处理非异常响应与 webexception 响应的?

c# - 用于登录 ASP.NET 网站的控制台应用程序

c# - 从 wcf c# 中的 URL 下载 zip 文件

c# - 将 WCF REST 服务托管为 Windows 服务

java - Spring中客户端向服务器端发送数据

c# - 从网站获取 Xml 文件

c# - 尝试将文件上传到 Ftp 但收到错误 : "file name not allowed"!