5

I'm having a hell of a time trying to figure out why the same line returns request body as string in Post() and an empty string in Put() and ultimately how to get the request body in Put().

[HttpPost]
public JsonResult Post()
{
    ...
    var todoJson = new StreamReader(Request.InputStream).ReadToEnd();
    ...
}

[HttpPut]
public JsonResult Put(int id)
{
    ...
    var todoJson = new StreamReader(Request.InputStream).ReadToEnd();
    ...

}

Based on ((System.Web.HttpInputStream)(Request.InputStream))._data._data i got in Put(), the byte values are in the request body, however I am failing to extract the content. Any help greatly appreciated.

Edit: The method from HttpRequest.InputStream documentation works in Post(), in Put() it returns a string "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0..." of Content-Length.

jan zegan
  • 1,629
  • 1
  • 12
  • 18

2 Answers2

11

I should've seen this earlier Request.InputStream.Position points to the end of the request body, so

Request.InputStream.Position = 0;

fixes the problem.

jan zegan
  • 1,629
  • 1
  • 12
  • 18
0

It's probably because HTTP Put isn't widely supported by browsers, as mentioned in the SO Post : Doing a HTTP PUT from a browser. You are probably best sticking to GET and POST for widest compatibility. However, I have heard of code that can use a raw HttpWebRequest to perform a put, such as outlined here by Jason DeFontes in this post:

        string json = "...";
        byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/");
        request.Method = "PUT";
        request.ContentType = "application/json";
        request.ContentLength = arr.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(arr, 0, arr.Length);
        dataStream.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        string returnString = response.StatusCode.ToString();
        Console.WriteLine(returnString);
Community
  • 1
  • 1
Dan Diplo
  • 25,076
  • 4
  • 67
  • 89
  • Thanks, that's good reading. I have seen this code and the thing is the browser is sending PUT. To be more clear I'm basically doing a RESTful handler for the backbone.js [todo](http://documentcloud.github.com/backbone/examples/todos/index.html) app, so all the GET, POST, PUT, DELETE requests are sent by backbone and work for the [same app](https://github.com/ccarpenterg/todolist/wiki) written for Google App Engine. So it appears the request body is there, I just can't read it. – jan zegan Jun 16 '11 at 10:25