这是提交post请求的页面
protected void Button1_Click(object sender, EventArgs e) { string json = GetReleseUserJson(); string str = HttpPost(json, "http://192.168.1.113/testapi/api/test"); Response.Write(str); } private string HttpPost(string postDataStr, string Url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/json"; //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); myStreamWriter.Write(postDataStr); myStreamWriter.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } //JSON字符串 public static string GetReleseUserJson() { string json = "{"; json += "\"ID\":5,"; json += "\"Name\":\"超大厦\","; json += "\"Age\":55"; json += "}"; return json; }
这是web API 控制器里的
public Test Post([FromBody]Test ttt) { return ttt; }
这是model里的
public class Test { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } }
可以试试HttpClient调用。
var data = JsonConvert.SerializeObject(test); var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var file = client.PostAsJsonAsync(url,data);
代码中test是Test的实例。
你POST的内容不带querystiring的.需要这样获取:
var s = Request.InputStream;
var b = new byte[s.Length];
s.Read(b, 0, (int) s.Length);
var postStr = Encoding.UTF8.GetString(b);
这样就可以获取到你传递的json内容了. postStr再序列化成你的对象即可