HttpWebRequest的Request.Form接收不到数据的说明

最近想用做webapi时候发现HttpWebRequest只有设置为application/x-www-form-urlencoded时候,接收端才能通过Request.Form["key"]来获取值,Js得ajax一样也需要设置contentType: "application/x-www-form-urlencoded;charset=utf-8"

当ContentType设置为application/json时,Request.Form是取不到任何值得。Keys的长度为0;

正确获取方式:

          var stream = Request.InputStream;
           stream.Position = 0; //如果使用mvc,必须设置,否则流position一直在最后,个人理解为mvc内部已经对Request.InputStream进行了读取导致position移到了最后。
           StreamReader streamReader = new StreamReader(stream);
           string body=streamReader.ReadToEnd();

或者

           var stream = Request.InputStream;
           stream.Position = 0;
           byte[] byts = new byte[stream.Length];
           stream.Read(byts, 0, byts.Length);
           string body = System.Text.Encoding.UTF8.GetString(byts);

得到的body就是json格式字符串,如:
{"httpUrl":"http://www.pageadmin.net/e/images/logo.jpg","saveFilePath":"/app_data/test/logo.jpg"}

原文地址:https://www.cnblogs.com/huaguo/p/8471215.html