最近开发了一个WebApi项目,需要再后台请求,发现进行POST调用时,参数始终传递不过去,经过各种尝试终于找到解决方法。
客户端:
1string strContent = "{'data':'123'}"; 2 string sss = HttpPost("http://192.168.1.128:8025/api/Demo/GetResult", strContent); 3 4 /// <summary> 5 /// GET请求 6 /// </summary> 7 /// <param name="url"></param> 8 /// <returns></returns> 9 public string HttpGet(string url) 10 { 11 Encoding encoding = Encoding.UTF8; 12 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 13 request.Method = "GET"; 14 request.Accept = "text/html, application/xhtml+xml, */*"; 15 request.ContentType = "application/json"; 16 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 17 18 using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) 19 { 20 return reader.ReadToEnd(); 21 } 22 } 23 24 /// <summary> 25 /// POST请求 26 /// </summary> 27 /// <param name="url"></param> 28 /// <param name="body"></param> 29 /// <returns></returns> 30 public static string HttpPost(string url, string body) 31 { 32 Encoding encoding = Encoding.UTF8; 33 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 34 request.Method = "POST"; 35 request.Accept = "text/html, application/xhtml+xml, */*"; 36 request.ContentType = "application/json"; 37 38 byte[] buffer = encoding.GetBytes(body); 39 request.ContentLength = buffer.Length; 40 request.GetRequestStream().Write(buffer, 0, buffer.Length); 41 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 42 using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) 43 { 44 return reader.ReadToEnd(); 45 } 46 }
服务端:
1using System.Web.Http; 2 3namespace WebApplication1.Controllers 4{ 5 public class DataInfo 6 { 7 public string data { get; set; } 8 } 9 10 public class DemoController : ApiController 11 { 12 [HttpPost] 13 public IHttpActionResult GetResult([FromBody]DataInfo data) 14 { 15 var result = new { data = data.data }; 16 return Json(result); 17 } 18 } 19}