7

I am trying to post some data from asp.net to webservice using http post.

While doing that I am getting the enclosed error. I have checked many post but nothing helps me really. Any help onto this will greatly appreciated.

Length = 'dataStream.Length' threw an exception of type 'System.NotSupportedException'

Position = 'dataStream.Position' threw an exception of type 'System.NotSupportedException'

Enclosed please my code:

public XmlDocument SendRequest(string command, string request)
{
    XmlDocument result = null;

    if (IsInitialized())
    {
        result = new XmlDocument();

        HttpWebRequest webRequest = null;
        HttpWebResponse webResponse = null;

        try
        {
            string prefix = (m_SecureMode) ? "https://" : "http://";
            string url = string.Concat(prefix, m_Url, command);

            webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = "text/xml";
            webRequest.ServicePoint.Expect100Continue = false;

            string UsernameAndPassword = string.Concat(m_Username, ":", m_Password);
            string EncryptedDetails = Convert.ToBase64String(Encoding.ASCII.GetBytes(UsernameAndPassword));

            webRequest.Headers.Add("Authorization", "Basic " + EncryptedDetails);

            using (StreamWriter sw = new StreamWriter(webRequest.GetRequestStream()))
            {
                sw.WriteLine(request);
            }

            // Assign the response object of 'WebRequest' to a 'WebResponse' variable.
            webResponse = (HttpWebResponse)webRequest.GetResponse();

            using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
            {
                result.Load(sr.BaseStream);
                sr.Close();
            }
        }

        catch (Exception ex)
        {
            string ErrorXml = string.Format("<error>{0}</error>", ex.ToString());
            result.LoadXml(ErrorXml);
        }
        finally
        {
            if (webRequest != null)
                webRequest.GetRequestStream().Close();

            if (webResponse != null)
                webResponse.GetResponseStream().Close();
        }
    }

    return result;
}

Thanks in advance !!

Ratika

IAbstract
  • 19,551
  • 15
  • 98
  • 146
NewGirlInCalgary
  • 71
  • 1
  • 3
  • 11
  • Base 64 encoding is not encryption. – David M May 15 '12 at 16:13
  • 1
    Where in your posted code are the lines that are erroring? There isn't even a variable called `dataStream`... – David M May 15 '12 at 16:15
  • Network streams do not support Length nor Position. – user703016 May 15 '12 at 16:15
  • I suspect those messages were seen in the debugger... no question here, NEXT! – leppie May 15 '12 at 16:34
  • I get these error on debugger on StreamWriter. I am not sure how to fix it. Can anyhelp help me with that please. – NewGirlInCalgary May 15 '12 at 17:06
  • This code was working perfectly fine couple of months ago. Now it stopped automatically and through the exception. By thinking it may be some issue with VS 2005 I have tried running this code on VS 2005, 2008, 2010 but it did not work any more. – NewGirlInCalgary May 15 '12 at 17:17
  • @leppie, probably right, but those errors can end up causing other ones. Like for me, I saw these while I was trying to read the bytes using `byte[] myBytes = new byte[1024]; stream.Read(myBytes, 0, myBytes.Length);` and got "Parameter is not supported". I suspected it was those parameters like seek and length being unsupported it was complaining about. – vapcguy Nov 08 '14 at 04:37

1 Answers1

10

When you call HttpWebResponse.GetResponseStream, it returns a Stream implementation that that doesn't have any recall ability; in other words, the bytes that are sent from the HTTP server are sent directly to this stream for consumption.

This is different from say, a FileStream instance in that if you want to read a section of the file that you've already consumed through the stream, the disk head can always be moved back to the location to read the file from (more than likely, it's buffered in memory, but you get the point).

With an HTTP response, you'd have to actually reissue the request to the server in order to get the response again. Because that response is not guaranteed to be the same, most of the position related methods and properties (e.g. Length, Position, Seek) on the Stream implementation passed back to you throw a NotSupportedException.

If you need to move backwards in the Stream, then you should create a MemoryStream instance and copy the response Stream into the MemoryStream through the CopyTo method, like so:

using (var ms = new MemoryStream())
{
    // Copy the response stream to the memory stream.
    webRequest.GetRequestStream().CopyTo(ms);

    // Use the memory stream.
}

Note, if you aren't using .NET 4.0 or later (where CopyTo on the Stream class was introduced) then you can copy the stream manually.

Community
  • 1
  • 1
casperOne
  • 73,706
  • 19
  • 184
  • 253
  • Thanks Casper for the help. I was trying using the above code but I couldn't use the CopyTo() properties. It is not showing me and letting me doing that with webRequest.GetRequestStream(). It does have CanRead, CanSeek, CanTimeOut,CanWrite properties. Do you know if I can do anything else ? – NewGirlInCalgary May 15 '12 at 21:55
  • @Ratika I assume you're not on version 4.0 of .NET? It was introduced in .NET 4.0. If that's the case, then you'll have to create a `byte[]` array manually or copy the stream to a `MemoryStream`. I've updated the answer to reflect this (see the last link). – casperOne May 15 '12 at 22:02
  • I have tried using byte[] array and MemoryStream but it did not copy anything. Instead it goes into catch exception. Do you any other suggestion ? – NewGirlInCalgary May 18 '12 at 17:44
  • @Ratika Without any details on how you actually tried to copy the stream, there's no way to tell. – casperOne May 18 '12 at 17:53
  • @ casperOne♦ Enclosed please find my code which I edit just before StreamWriter: byte[] buffer = new byte[16*1024]; int bytesRead; using (var memStream = new MemoryStream()) { while ((bytesRead = webRequest.GetRequestStream().Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, bytesRead); } } – NewGirlInCalgary May 22 '12 at 15:37
  • @Ratika The link I've posted at the end shows how to correctly copy the streams. – casperOne May 22 '12 at 15:39
  • @ casperOne♦ I am sorry I could not get you. Do you think there is any problem with the code I am using for byte[]? Since I have used the code from the link which you have provided me. byte[] buffer = new byte[16*1024]; int bytesRead; using (var memStream = new MemoryStream()) { while ((bytesRead = webRequest.GetRequestStream().Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, bytesRead); } } – NewGirlInCalgary May 22 '12 at 16:45