WebClient 在winxp win2003下的奇怪问题
byte[] buffer=Encoding.UTF8.GetBytes("email="+userEmail+"&password="+pwd);
string result = Encoding.UTF8.GetString(new WebClient().UploadData("http://www.51dns.com",buffer));
代码很简单,其实只是post了一点数据而已
但却收到以下异常
这是怎么回事?
------解决方案--------------------The problem is redirection by the webs
Unfortunately you have to subclass WebClient to fix this. This is harder than it looks because Silverlight (any flavour) doesn't like this and throws an inheritance related exception until you guess that you need to override the ctor and attribute it as SecurityCritical.
public class WebClient2 : WebClient
{
[SecurityCritical]
public WebClient2() : base() { }
protected override WebRequest GetWebRequest(System.Uri address)
{
var wr = base.GetWebRequest(address);
if (wr is HttpWebRequest)
(wr as HttpWebRequest).AllowAutoRedirect = false;
return wr;
}
}
If you want to go further you could surface an AllowAutoRedirect property on WebClient2 and hook it all up.
代码和解释来自stackoverflow
Why does this exception claim the code doesn't write data?
http://stackoverflow.com/questions/6636009/why-does-this-exception-claim-the-code-doesnt-write-data