Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Request Body in ASP.NET

How does one read the request body in ASP.NET? I'm using the REST Client add-on for Firefox to form a GET request for a resource on a site I'm hosting locally, and in the Request Body I'm just putting the string "test" to try to read it on the server.

In the server code (which is a very simple MVC action) I have this:

var reader = new StreamReader(Request.InputStream);
var inputString = reader.ReadToEnd();

But when I debug into it, inputString is always empty. I'm not sure how else (such as in FireBug) to confirm that the request body is indeed being sent properly, I guess I'm just assuming that the add-on is doing that correctly. Maybe I'm reading the value incorrectly?

like image 270
David Avatar asked Sep 01 '11 18:09

David


People also ask

How do I get a request body in middleware?

To read the request body in ASP.NET Core Web API, we will create a custom middleware. Visual Studio gives you a readymade template to create custom middleware. Right-click on your project in Solution Explorer and click “Add New Item”. In the search box type “Middleware” and you will see Middleware Class in the result.

What is FromBody ASP NET core?

[FromBody] attributeThe ASP.NET Core runtime delegates the responsibility of reading the body to an input formatter. Input formatters are explained later in this article.

How do I read a request body in .NET core?

Position = 0; var rawRequestBody = new StreamReader(Request. Body). ReadToEnd();

What is body of a request?

A request body is data sent by the client to your API. A response body is the data your API sends to the client. Your API almost always has to send a response body. But clients don't necessarily need to send request bodies all the time.


1 Answers

Maybe I'm misremembering my schooling, but I think GET requests don't actually have a body. This page states.

The HTML specifications technically define the difference between "GET" and "POST" so that former means that form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body.

So maybe you're doing things correctly, but you have to POST data in order to have a message body?

Update

In response to your comment, the most "correct" RESTful way would be to send each of the values as its own parameter:

site.com/MyController/MyAction?id=1&id=2&id=3...

Then your action will auto-bind these if you give it an array parameter by the same name:

public ActionResult MyAction(int[] id) {...}

Or if you're a masochist you can maybe try pulling the values out of Request.QueryString one at a time.

like image 99
StriplingWarrior Avatar answered Oct 07 '22 04:10

StriplingWarrior