c# webapi POST 引數解決方法
HttpWebRequest POST請求webapi:如果引數是簡單型別,比如字串(注意,拼接的字串要HttpUtility.UrlEncode才行,否則服務端會丟失特殊字元&後面的資料)
要點:如下程式碼統一設定為:ContentType = "application/x-www-form-urlencoded";
服務端程式碼1:URL格式為 POSTapi/Values
public string Post([FromBody] string value)
則客戶端Post的資料:拼接的字串必須以 =開頭,否則服務端無法取得value。例如:=rfwreewr2332322232 或者
服務端程式碼2:URL格式為 POST api/Values?value={value}
public string Post(string value)
則客戶端Post的資料:需要url裡拼接出KeyValue這樣的資料
服務端程式碼3:URL格式為 POSTapi/Values
public string Post()
則客戶端Post的資料:無要求。例如:key=rfwreewr2332322232。
服務端:可以用HttpContext.Current.Request.InputStream或者HttpContext.Current.Request.Form[0]都可以獲取
如果post的引數型別比較複雜,則需要自定義類
要點:如下程式碼統一設定為:ContentType = "application/json";
服務端程式碼1:URL格式為 POSTapi/Values
public string Post([FromBody] Model value)或者 public string Post(Model value)
則客戶端Post的資料:{\"id\":\"test1\",\"name\":\"value\"}。服務端會自動對映到物件。
提交程式碼如下:
服務段程式碼如下:HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://localhost:37831/api/Values"); wReq.Method = "Post"; //wReq.ContentType = "application/json"; //wReq.ContentType = "application/x-www-form-urlencoded"; wReq.ContentType = "application/json"; //byte[] data = Encoding.Default.GetBytes(HttpUtility.UrlEncode("key=rfwreewr2332322232&261=3&261=4")); byte[] data = Encoding.Default.GetBytes("{\"id\":\"test1\",\"name\":\"value\"}"); wReq.ContentLength = data.Length; Stream reqStream = wReq.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); using (StreamReader sr = new StreamReader(wReq.GetResponse().GetResponseStream())) { string result = sr.ReadToEnd(); }
// POST api/values
//public string Post()
//{
// FileInfo fi = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log.txt");
// StreamWriter sw = fi.CreateText();
// StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream);
// sw.WriteLine("1:" + sr.ReadToEnd()+"--"+ HttpContext.Current.Request.Form[0]);
// sw.Flush();
// sw.Close();
// return "{\"test\":\"1\"}";
//}
// POST api/values
public HttpResponseMessage PostStudent(Student student)
{
FileInfo fi = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log.txt");
StreamWriter sw = fi.AppendText();
sw.WriteLine("2:" + student.id);
sw.Flush();
sw.Close();
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent("{\"test\":\"2\"}", Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
這篇文章裡有的方法也不錯:http://www.cnblogs.com/rohelm/p/3207430.html