我遇到错误Stream.Length抛出NotSupportedException

时间:2013-11-13 06:16:16

标签: c# asp.net stream httpwebresponse system.net.httpwebrequest

我正在尝试使用HttpWebRequest对象将一些来自ASP.Net应用程序的数据发布到PHP。但是当我尝试使用

阅读Request内容时
Stream myStream = myWebReq.GetRequestStream();

我收到错误

  

'responseStream.Length'抛出了'System.NotSupportedException'类型的异常。
  Length ='dataStream.Length'引发了'System.NotSupportedException'类型的异常   Position ='dataStream.Position'引发了类型'System.NotSupportedException'的异常

这是代码

string strURL = null;
HttpWebRequest myWebReq = default(HttpWebRequest);
HttpWebResponse myWebResp = default(HttpWebResponse);

byte[] byteData = null;
StreamReader sr = default(StreamReader);
strURL = "http://people.com.pk/nppm/hrms_ppm_service.php?dump=1";
myWebReq = (HttpWebRequest)WebRequest.Create(strURL);
myWebReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
myWebReq.Method = "POST";

Label1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(batches).ToString();

byteData = UTF8Encoding.UTF8.GetBytes(Label1.Text);
myWebReq.ContentLength = byteData.Length;

myWebReq.KeepAlive = true;

if (myWebReq.Proxy != null)
{
   myWebReq.Proxy.Credentials = CredentialCache.DefaultCredentials;
}

Stream myStream = myWebReq.GetRequestStream();

if (byteData.Length > 0)
{
   myStream.Write(byteData, 0, byteData.Length);
   myStream.Close();
}

myWebResp = (HttpWebResponse)myWebReq.GetResponse();
sr = new StreamReader(myWebResp.GetResponseStream());
string strJSON__2 = sr.ReadToEnd();
Label1.Text = strJSON__2;

1 个答案:

答案 0 :(得分:0)

只需查看您的HttpWebRequest.DefaultCachePolicy财产 正如documentation建议仅当请求缓存验证程序指示可以从缓存提供请求的响应时, HttpWebRequest.GetRequestStream 方法才会抛出NotSupportedException;但是,写入数据的请求不得使用缓存。如果您使用的是错误实现的自定义缓存验证程序,则会发生此异常。