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 或者 {'':value}

 

服務端代碼2:URL格式為 POST api/Values?value={value}

public string Post(string value)

則客戶端Post的數據:需要url里拼接出KeyValue這樣的數據

服務端代碼3:URL格式為 POST api/Values

public string Post()

則客戶端Post的數據:無要求。例如:key=rfwreewr2332322232。

服務端:可以用HttpContext.Current.Request.InputStream或者HttpContext.Current.Request.Form[0]都可以獲取

 

如果post的參數類型比較復雜,則需要自定義類

要點:如下代碼統一設置為:ContentType = "application/json";

服務端代碼1:URL格式為 POST api/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;  
}  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM