Search code examples
c#.net-4.0portable-class-library

POST/PUT request with Portable Library


We've created a Portable Class Library project to write a client/wrapper/proxy project for our ASP.NET Web Api Rest service.

I'll get straight to it: It seems we can not do POST/PUT requests which have a body.

var dataBytes = Encoding.UTF8.GetBytes(data);

var requestHandle = request.BeginGetRequestStream(ar =>
{
    using (var stream = request.EndGetRequestStream(ar))
    {
        stream.Write(dataBytes, 0, dataBytes.Length); // Exception thrown here
    }
}, null);

As soon as I try to write to the request, I get an exception:

The request was aborted: The connection was closed unexpectedly.

After a bit of time, I figured that stream.CanWrite is false, so it's not writable, which pretty much means we can not do any POST requests with a body.

Can someone help us out here and tell us how we're supposed to do the POST requests? I found another post here where the answer was to take a look at RestSharp but that doesn't seem to work either since it does not support Portable Library.

Any help is appreciated.


Solution

  • This doesn't look like a problem specific to a Portable Class Library. If you run the same code in a platform-specific library, I expect it would fail in the same way. So I expect that the issue is either with the way you are creating or using HttpWebRequest, or perhaps something on the server side.

    What platform are you running this on and getting the failure?

    You may want to look at the Async Targeting Pack (more info). This will add async and await support as well as some extension methods such as GetRequestStreamAsync(), so you would be able to use the following code (inside an async method):

    using (var stream = await request.GetRequestStreamAsync())
    {
        stream.Write(dataBytes, 0, dataBytes.Length);
    }
    

    The behavior should be the same though so I don't expect this by itself will fix your problem.