Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading PUT Request Body

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.

like image 382
jan zegan Avatar asked Jun 16 '11 09:06

jan zegan


People also ask

Should a PUT request have a body?

If the request has a Content-Length header, then it has a body. It may be an empty body, but still a body. In contrast to a request with no Content-Length header, which has no body at all, not even an empty one. So yes, a PUT request, technically, strictly, has to have a body.

How do I pass BODY IN PUT request?

You can send data to the server in the body of the HTTP PUT request. The type and size of data are not limited. But you must specify the data type in the Content-Type header and the data size in the Content-Length header fields. You can also post data to the server using URL parameters with a PUT request.


1 Answers

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.

like image 107
jan zegan Avatar answered Sep 26 '22 18:09

jan zegan