简体   繁体   English

如何使用.NET C#从POST处理和获取正文?

[英]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? 因此,我知道如何通过使用Request.Form["abc"]来获取表单数据,但是如何通过获取正文来获取表单数据呢?

I've used this snippet in the below link: 我在以下链接中使用了此代码段:

https://gist.github.com/leggetter/769688 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'); 在PHP中可以这样做: 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. 注意:POST的内容类型为application / json,主体包含json字符串。

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: 如果我正确理解了您的问题,则可以在将其发布到您希望获得JSON响应的资源时执行以下操作:

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. 由于您的问题没有指定您是否需要知道如何解析JSON本身,因此我省略了JSON解析的示例。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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