简体   繁体   中英

How to handle and get the body from POST using .NET C#?

So, I know how to get form data out by using Request.Form["abc"] however how would I go by getting the body out?

I've used this snippet in the below link:

https://gist.github.com/leggetter/769688

But, I'm not sure what to pass in as the Response.

In PHP to do this: file_get_contents('php://input'); and it's as simple as that.

Notes: The content type of the POST is application/json and the body contains the json string.

Thanks in advance.

If I understood your question correctly, here's what you could do when posting to a resource for which you expect a JSON response:

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://foo.com/bar/");
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json";

HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

//store json in a variable for later use
string json = readStream.ReadToEnd();

//make sure to close
response.Close();
readStream.Close();

Of course, this approach is synchronous; but, depending on your requirements, this might be just fine.

Since your question didn't specify whether you need to know how to parse the JSON itself, so I've left out an example of JSON parsing.

You'll need code similar to this to read the raw request body into a string variable.

using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
    string text = reader.ReadToEnd();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM