【问题标题】:I'm facing the error Stream.Length throws NotSupportedException我面临错误 Stream.Length throws NotSupportedException
【发布时间】:2013-11-25 15:17:09
【问题描述】:

我正在尝试使用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;

【问题讨论】:

  • 你能把 excpetion 的完整堆栈跟踪发布到它抛出 excpetion 的那一行吗....
  • 例外在这里...Stream myStream = myWebReq.GetRequestStream(); Length = 'dataStream.Length' 引发了 'System.NotSupportedException' 类型的异常 Position = 'dataStream.Position' 引发了 'System.NotSupportedException' 类型的异常

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


【解决方案1】:

只需检查您的 HttpWebRequest.DefaultCachePolicy 属性即可。
正如documentation 建议的那样,HttpWebRequest.GetRequestStream 方法只会在请求缓存验证器指示可以从缓存中提供请求的响应时抛出NotSupportedException;但是,写入数据的请求不得使用缓存。如果您使用了未正确实现的自定义缓存验证器,则可能会发生此异常。

【讨论】:

  • 已经通过以下几行清除缓存...HttpWebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);仍然有问题是“NotSupportedException”
  • 试试这个,myWebReq.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); //RequestCacheLevel应该是BypassCache
  • @devanalysts 我粘贴了你的代码,这在我的机器上运行良好
  • 我尝试了两台机器,但异常仍然是“Stream.Length throws NotSupportedException”。
  • @devanalysts 你说错误在这里 Stream myStream = myWebReq.GetRequestStream(),但是在你发布的堆栈跟踪中,有问题的'responseStream.Length'抛出了一个'System.NotSupportedException'类型的异常??? ??你没有正确粘贴的东西....
猜你喜欢
  • 2011-03-23
  • 2023-02-05
  • 2020-07-25
  • 2016-12-07
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多