C#异常 "This stream does not support seek operations." 对于HttpWebRequest方法 "PUT"

3
我是一名有用的助手,可以为您翻译文本。以下是需要翻译的内容:

enter image description here 我正在使用PUT方法更新一些数据。但我的下面代码无法工作。

代码:

var schemaRequest = WebRequest.Create(new Uri(SchemaUri)) as HttpWebRequest;
schemaRequest.Method = "PUT";
schemaRequest.ContentType = "text/xml";
schemaRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
schemaRequest.Proxy = WebRequest.DefaultWebProxy;
schemaRequest.AddRange(1024);

string test = "<ArrayOfUpdateNodeRequest> <UpdateNodeRequest>  <Description>vijay</Description> <Name>Publishing</Name></UpdateNodeRequest></ArrayOfUpdateNodeRequest>";

byte[] arr = new byte[1024];
arr = System.Text.Encoding.UTF8.GetBytes(test);
schemaRequest.ContentLength = arr.Length;

using (var dataStream = schemaRequest.GetRequestStream())
{
    dataStream.Write(arr, 0, arr.Length);
}

我遇到了异常情况:“此流不支持寻求操作。”,出现在 GetRequestStream() 方法中。

你能否张贴异常堆栈跟踪信息? - Thomas Levesque
你的帮助有点过多了。请移除 ContentLength 赋值。 - Hans Passant
@HansPassant - 我不认为这是原因(可能性存在,但据我理解应该双向工作)。可能是服务器不接受带有范围的POST请求的问题吗? - Alexei Levenkov
嗨,Thomas,我上传了异常堆栈跟踪。 - user3194721
3
只有在调试时查看“Position”属性时出现异常吗?如果是这样,那很正常......你的代码似乎没有访问流的位置,“Position”应该能够正常运行。 - Thomas Levesque
显示剩余2条评论
1个回答

1

异常情况很清晰,流不支持寻址。在调试器中查看对象并不意味着您需要寻址——如果确实需要,请提供示例。您应该能够将数据写入流中以发送到主机。当您将流发送到主机时,无法寻址是有道理的(例如,如何在已经发送到主机的字节之前进行寻址?)。

如果需要在发送到主机之前进行本地寻址,请创建一个内存流并以此方式进行寻址。例如:

using (MemoryStream memoryStream new MemoryStream())
{
    // ... writes
    memoryStream.Seek(0, SeekOrigin.Begin);
    //... writes
    memoryStream.CopyTo(schemaRequest.GetRequestStream());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接