最近开发了一个WebApi项目,需要再后台请求,发现进行POST调用时,参数始终传递不过去,经过各种尝试终于找到解决方法。
客户端:
string strContent = "{'data':'123'}";
string sss = HttpPost("http://192.168.1.128:8025/api/Demo/GetResult", strContent);
/// <summary>
/// GET请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string HttpGet(string url)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <returns></returns>
public static string HttpPost(string url, string body)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
服务端:
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class DataInfo
{
public string data { get; set; }
}
public class DemoController : ApiController
{
[HttpPost]
public IHttpActionResult GetResult([FromBody]DataInfo data)
{
var result = new { data = data.data };
return Json(result);
}
}
}