Search code examples
c#.nethttpwebrequestwebrequestportable-class-library

Portable Class Libraries & WebRequest.ContentLength


I have a Portable Class Library that targets ".NET for Windows Store apps" and "Windows Phone 7.5 or higher". I make HTTP POST requests and as of last week, the admins in charge of the back-end decided that I need to send a ContentLength of 0 as opposed to -1 that is defaulted by .NET. I use the WebRequest class but i'm flexible enough to use HttpWebRequest if needed.

Normally I would just use WebRequest.Create and set the ContentLength property. In the PCL library, the ContentLength property is not available. If I try to add a Header with a key of "Content-Length" the framework complains that I should just use the ContentLength property.

Any ideas on how I can set the ContentLength in a PCL?


Solution

  • If you can't set the ContentLength property but it must be set to 0 you may try to call GetRequestStream (or BeginGetRequestStram followed by EndGetRequestStream) without writing anything to the Stream itself, this should update ContentLength property to its actual value (0, because nothing has be written).