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

 I cannot figure out why when I expand the requestStream variable that I see that error.  Here's my code:

  

               ...
                request.Timeout = 30000;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                // write data to stream
                byte[] requestBytes = Encoding.UTF8.GetBytes(request.ToString());

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(requestBytes, 0, requestBytes.Length);
                    requestStream.Close();
                }
....
 
0
espresso
1/16/2009 8:27:52 PM
asp.net.getting-started 91979 articles. 2 followers. Follow

15 Replies
3569 Views

Similar Articles

[PageSpeed] 47

 

I don't believe this is supported for System.IO.Stream.  They just provide a template that you can overwrite if you create a class that inherits the stream and you want to create your own Length property to go with it.

The tooltip says: "When overridden in a derived class, gets the length in bytes of the stream."

 

 

0
hayedid
1/16/2009 8:40:47 PM

 But this is the standard way I see people have sent the stream for a web request.  Microsoft shows their example here: http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

Here's my method:

  

public static HttpWebResponse SendRequest(WebRequest request)
{
HttpWebResponse response;

request.Timeout = 30000;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

byte[] requestBytes = Encoding.UTF8.GetBytes(request.ToString());
request.ContentLength = requestBytes.Length;

using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
}

response = (HttpWebResponse)request.GetResponse();

if (response == null)
throw new NullReferenceException("Response recieved was null");

return response;
}
 
in the end, I ultimately get an Http error of 500 from above. 
 
0
espresso
1/16/2009 8:45:12 PM

 

Sorry.  I may have misunderstood something.  The code itself doesn't try to call requestStream.Length.  As I understand it, you are doing this within the IDE.  I don't believe Length is supported unless it's overridden by a derived object.  Is the code you've pasted above causing a problem that you are trying to debug?

 

0
hayedid
1/16/2009 8:54:21 PM

 This is just a web request sent to a third party rest API.  I'm just trying to send the web request to the 3rd party server. That's all this is.  I have a button wired up and a bunch of methods run, create the request and then this is the last method that's fired.  Pretty common stuff.

0
espresso
1/16/2009 9:29:41 PM

 shyat.  I need to use HttpWebRequest.

0
espresso
1/16/2009 9:39:43 PM

I understand; however, is your code producing an error?  I'd like to try to help,  Your messages seem to indicate that your code is not working; but your question is regarding something easily explained by the implementation of System.IO.Stream.  This is likely a separate issue than whatever is going on in your code. 

-2
hayedid
1/16/2009 9:39:46 PM

 Thanks. Problem is still there.  The original error is in the subject.  When I mouse over and expand the requestStream variable after it's set, I see the followinf for 2 of its properties:

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

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

here is the same thing, an example of what I'm doing here: http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

0
espresso
1/16/2009 9:49:07 PM

 Here, take a look at my screen shot: www.elbalazo.net/posts/error.jpg

0
espresso
1/16/2009 10:00:16 PM

 

.Length is not supported for requestStream.  neither is .Position.  That is why you are getting these messages when hovering.  If you remove your exception handling routine and run your code again, it should throw an error if it's not working.  That's the error you will need in order to figure out what's going on.  The error you are are getting while hovering has nothing to do with the code working or not working.

It sounds like you might be getting frustrated, but I believe you're barking up the wrong tree, so to speak, with the request.Stream exceptions.

 

0
hayedid
1/16/2009 10:00:26 PM

 >>>.Length is not supported for requestStream.  neither is .Position.  That is why you are getting these messages when hovering.  If you remove your exception handling routine and run your code again, it should throw an error if it's not working.  That's the error you will need in order to figure out what's going on.

 Then why is it being used in many applications (one our side) and many more  as well as Microsoft shows an example using it the same way I have my code as well!  I do not have any exception handling around that.  So this has to be valid.  Otherwise the stream will not be filled with the reqest data.

0
espresso
1/16/2009 10:03:45 PM

 Maybe I do not need to worry about those errors.  It seems like the request has data to be sent.  But I just saw those and I do not think it's good in the stream.  The stream has to have this, there are a ton of examples with the same code I have right here!  I just want to know why and if I can ignore them and still send this request

0
espresso
1/16/2009 10:12:23 PM

Your code uses requestBytes.Length, not requestStream.Length.  The requestStream.Length is not a problem.  Perhaps the 500 error is being caused by the fact that your are overwriting "response".  You might try to define an "HttpWebResponse resp" instead.  As far as I know, response is reserved

0
hayedid
1/16/2009 10:19:48 PM

 I'm picking up a 500 error because the remote server is receiving it and processing it and returning the 500.  So looks like my request is being sent ok.

0
espresso
1/17/2009 4:20:58 AM

Hi,

   I am having the same issue as you do, except that I have error trapping in my code, and it's giving me a WebException type of error, when the call to GetRequestStream is made in the HttpWebRequest instance.

   Were you able to resolve this error?

    Thanks,

    Dan.

 

0
xman71
1/22/2009 3:34:17 PM

Dan and all,

I see the "NotSupportedException" errors in my datastream properties for length and position when I set a breakpoint, but my POST still works successfully (after some trial and error).  I am using an XML payload (content-type="text/xml") though, which is slightly different from your example.

One gotcha for anyone using XML payloads for your post data - make sure you specify a namespace in your root element.  I was getting an "Accepted" (response code 202) back from a WCF REST web service on a POST attempt, which wasn't not succesfully updating my data.  Once I added the namespace property I received the "OK" (200) message and things worked fine.

For what it's worth here's a code snippet that I have that works for the POST function (I also referenced the example from Microsoft: http://msdn.microsoft.com/en-us/library/debx8sh9.aspx):

XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration =
true;
string xml;

using (StringWriter sw = new StringWriter())
{

using (XmlWriter xw = XmlWriter.Create(sw, xws))
{
xw.WriteStartElement(
"SessionRequest", "http://tempuri.org/temp/Session");  //must specify namespace
xw.WriteElementString(
"AppName", "test app name");
xw.WriteElementString(
"Category", "test category");
xw.WriteEndElement();
xw.Close();
}

xml = sw.ToString();
sw.Close();
}

ASCIIEncoding encoding = new ASCIIEncoding();
byte[] PostData = encoding.GetBytes(xml);
Uri serviceUri = new Uri(String.Format("http://localhost:1128/Q2.svc/Session({0})", SessionID));

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUri);
request.Method =
"POST";
request.ContentType =
"text/xml";
request.ContentLength = PostData.Length;

Stream dataStream = request.GetRequestStream();
dataStream.Write(PostData, 0, PostData.Length);
dataStream.Close();

WebResponse response = request.GetResponse();

0
Ty
3/10/2009 7:21:26 PM
Reply:

Similar Artilces:

''''''''''''''''''''
Name: haznen Email: haznenatyahoodotcom Product: Gran Paradiso Alpha 8 Summary: '''''''''''''''''''' Comments: '''''''''''''''''''''''''''''''''''' Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) Gecko/20061204 UGES/1.7.2.0 GranParadiso/3.0a1 From URL: http://www.mozilla.org/projects/granparadiso/ Note to readers: Hendrix gives...

'ds.SqlCacheDependency' threw an exception of type 'System.NotSupportedException'
Hi guys, As a follow up on my previous question: http://forums.asp.net/t/1336003.aspx I would like to know if any of you have an answer to the problem with the SqlCacheDependency throwing an System.NotSupportedException when trying to update using an AccessDataSource? Thanks :) /Ole   Since the SqlCacheDependency is not supported by Access, any attempt to make use of it through an AccessDataSource control will result in a NotSupportedException: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.accessdatasource.sqlcachedependency.aspx.  The mystery is why ...

'''''
Name: mario Email: ramar17atfastwebnetdotit Product: Gran Paradiso Alpha 2 Summary: ''''' Comments: K: Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a2) Gecko/20070206 GranParadiso/3.0a2 ...

Cast from type ''''DBNull'''' to type ''''String'''' is not valid.
How do I avoid getting this error: Cast from type ''''DBNull'''' to type ''''String'''' is not valid. I am trying to get values from the database into a form for updating using a Datareader, SQL is set to allow nulls for certain fields as they are not required but the only way I can get the form to display is by adding a space in SQL. Is there another way around this? Check if it is equal to DBNull.Value first and if it is, don't do the cast.Stanley Tan theSpoke Blog Where in the code does it need to go? I am using the following and it's the profile that isn't always requi...

table_info('','','','%') cannot return any types
I was recently confirming table_info special cases and discovered the case for getting table_types cannot work. table_info('','','','%') should return a list of table types but it returns a list of empty strings instead: my @types = $h->tables('', '', '', '%'); print "all types:\n", join("xxx\n", @types), "\n"; # should output something like: # "dbo" # "INFORMATION_SCHEMA" # "sys" # and actually outputs: xxx xxx It seems to be down to the following ...

'type' does not contain a definition for 'length'
Could anybody help me with this, thanks so much //Copyright (C) 2000 Microsoft Corporation. All rights reserved. // Hello1.cs public class Hello1 { int OneToZero(int[] args) { int iCount = 0; for (int i=0; i < args.length ; i++) { if (args[i] == 1) { iCount++; args[i] = 0; } } return iCount; } public static void Main(string[] args) { int[] iArr = {1, 3, 4, 5, 1, 1, 7}; Hello1 test = new Hello1(); int iNumOnes; System.Console.WriteLine("Values of the array: [ "); ...

'do' won't 'do' if '/'
Greetings to All from Au, Have a NetWare Perl 5.8.4 and wanted to tweak File\Spec\NW.pm to try and standardise on '/' separators. If I run a test script (t/uni/lower.t) with an unmodified NW.pm, it calls t/uni/case.pl, that, in case.pl, (when the path separators are '\'), the $file is '..\lib\unicore\To\Lower.pl' and the following code portion works, with $simple getting a returned table: sub casetest { my ($base, $spec, $func) = @_; my $file = File::Spec->catfile(File::Spec->catdir(File::Spec->updir, "lib", &qu...

'''
Name: L Lachowsky Email: e2brutus_10atyahoodotcom Product: Firefox Summary: ''' Comments: why duddn this surprise me... I change default server from IE to Mozilla, and then i get error messages. well, shud I decide to not get on my computer with Mozilla..or shud I risk security breeches with IE....hmmm at least i can get on the internet with IE Browser Details: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5 From URL: http://hendrix.mozilla.org/ Note to readers: Hendrix gives no expectation of a response to this fee...

Value of type 'System.Net.Mail.MailMessage' cannot be converted to 'System.Net.Mail.AlternateView'
Trying to create an alternateview to send a txt email with the html formatted email.  I've used string builder to create the whole email, but I get this error.  Any ideas why?  i've bolded the line that throws the error... Dim EmailBodyTxt As New StringBuilder EmailBodyTxt.Append("<html><style type='text/css'>.table{border:solid; border-color:#006666; width:600;} ")EmailBodyTxt.Append("<body><table class='table'><tr><td colspan='2'><h1>Test<br />RESPONSE SYSTEM</h1></td>...

'Sybase.Data.AseClient.AseConnection.DriverVersion' threw an exception of type 'System.TypeInitializationException'
'Sybase.Data.AseClient.AseConnection.DriverVersion' threw an exception of type 'System.TypeInitializationException' This is an error which I am getting while instantiating AseConnection. Can I get help on this exception. I am using C# in Visual Studio 2005. I checked the version in the C:\Program Files\Sybase\OC12_5_1\ADO.NET\dll folder of Sybase.Data.AseClient.dll and sybdrvado11.dll and copied these dlls to my application's bin folder. The versions are the same. Still I am getting the above exception. Whats this code look like? Are you sure both DLLs are sa...

Cannot convert type 'type' to 'type'
I am learning all of this, so I am still fresh, so please bear with me :)I have a page that has some txtboxes in it, simple registration form, and I have a button that will save those txt boxes to the db. I am using:- I am using Visual Web Developer 2008 Express Edition- C# When I try to compile the project I get error: Cannot convert type 'System.Web.UI.WebControls' to 'String' This is content of my web.config    <profile> <properties> <add name="FirstName"/> <add name="LasttName"/>...

Operator '*' is not defined for type 'DBNull' and type 'Decimal'.
 I am getting an error from the following line   <asp:Label ID="Label1" runat="server" Text='<%# String.Format("{0:C}", Eval("ProductQty") * Eval("Price"))   %>' ></asp:Label> I think I may need to convert/define the Variables but not quite sure how to do it. Any help would be great. it's not a matter of converting...its the fact that the value from the DB is Null... You'll have to wrap an IF check around it or change your query to return 0 instead of Null. If the field ...

Operator '=' is not defined for type 'Char' and type 'Boolean'.
Hello, In my application when i click the button i'm getting this " Operator '=' is not defined for type 'Char' and type 'Boolean'. " But when i test it locally there is no problem at all!!!! Please tell me why this error is occuring...Thanks SwapnaPlease click "mark as answer" if this post helped you. swapnasamsonvarkey: Hello, In my application when i click the button i'm getting this " Operator '=' is not defined for type 'Char' and type 'Boolean'. " But when i test it lo...

How do I get around this error "Unable to cast object of type 'System.DBNull' to type 'System.String' "
I am using Visual Developer 2008 Express Edition for the first time, and I keep getting the following error below. The site allows anyone to enter with a valid username and password, but even when I logoff the site I get the same error....like the memory or database is not getting refreshed. I would think that when I initially compile the site that anything left in memory would be flushed out. Can someone please help me to figure this out. Thanks,Ramell P.S. The site is programmed using C#    Unable to cast object of type 'System.DBNull' to type 'System.String&...

Web resources about - Length = 'requestStream.Length' threw an exception of type 'System.NotSupportedException' - asp.net.getting-started

Resources last updated: 2/11/2016 3:43:05 AM