C# 解決HttpWebRequest後臺POST請求調用WebApi參數傳遞問題

最近開發了一個WebApi項目,須要再後臺請求,發現進行POST調用時,參數始終傳遞不過去,通過各類嘗試終於找到解決方法。html

 

客戶端:json

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

服務端:api

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); } } }
相關文章
相關標籤/搜索