webclient和expect100继续

使用WebClient(C#.NET)时设置expect100continue的最佳方法是什么。 我在下面有这个代码,我仍然看到100继续在标题中。 愚蠢的apache仍抱怨505错误。

string url = "http://aaaa.com"; ServicePointManager.Expect100Continue = false; WebClient service = new WebClient(); service.Credentials = new NetworkCredential("username", "password"); service.Headers.Add("Content-Type","text/xml"); service.UploadStringCompleted += (sender, e) => CompleteCallback(BuildResponse(e)); service.UploadStringAsync(new Uri(url), "POST", query); 

注意:如果我将上述内容放在控制台应用程序中并让它运行 – 那么我在fiddler中看不到标题。 但是,我的代码嵌入在由WPF应用程序加载的用户库中。 那么,在线程,初始化等方面还有更多的Expect100Continue。现在,我认为这更多是我的代码问题。

您需要在用于访问的URI的ServicePoint上设置Expect100Continue属性:

 var uri = new Uri("http://foo.bar.baz"); var servicePoint = ServicePointManager.FindServicePoint(uri); servicePoint.Expect100Continue = false; 

将Expect100Continue更改为false后,尝试创建WebClient实例。 或者使用Webrequest而不是WebClient

执行此操作的唯一方法是创建覆盖。

  public class ExpectContinueAware : System.Net.WebClient { protected override System.Net.WebRequest GetWebRequest(Uri address) { System.Net.WebRequest request = base.GetWebRequest(address); if (request is System.Net.HttpWebRequest) { var hwr = request as System.Net.HttpWebRequest; hwr.ServicePoint.Expect100Continue = false; } return request; } } 

这很完美。

我的下面一种方法也奏效了,

在我的类(服务调用)的构造函数中,您可以设置System.Net.ServicePointManager.Expect100Continue = false;

然后我创建了BasicHttpBinding对象并继续,它执行成功。