WebApi Post引數物件,伺服器端引數物件為空的問題
阿新 • • 發佈:2019-02-04
最近在研究WebApi,在實際的工作中遇到了一個問題:在將引數物件MSG2的例項通過Post至伺服器端的時候,
伺服器端接收到的引數例項化結果總是為空:public static string SetMessageOperationResult(MSG2 model) { string result = string.Empty; if (model == null) return result; Hashtable ht = new Hashtable(); ht.Add("Authorization", string.Format("Bearer {0}", _accToken)); var content = JsonConvert.SerializeObject(model); string url = string.Format("{0}{1}", _baseUrl, _setMessageOperationResult); result = HttpHelper.PostData(content, url, _timeout, ht); return result; }
<pre name="code" class="csharp"> [HttpPost]
public async Task<MSG2ReturnModels> SetMessageOperationResult(MSG2 MSG2)
{
if(MSG2 == null) //一直成立
我一遍又一遍的檢查程式碼,嘗試著各種解決辦法,包括[FromBody] \ [FromURL] ,各問題依舊。。。。。。
一直到了下午,吃過了午飯,在小夥伴的一次次幫助下,最終我發現了問題的所在:
如果紅色的兩個引數不傳,我的方法預設這兩個引數的值為:"application/x-www-form-urlencoded" 和 "application/json",則伺服器端將會獲取不到客戶端傳遞過來的值public static string SetMessageOperationResult(MSG2 model) { string result = string.Empty; if (model == null) return result; Hashtable ht = new Hashtable(); ht.Add("Authorization", string.Format("Bearer {0}", _accToken)); var content = JsonConvert.SerializeObject(model); string url = string.Format("{0}{1}", _baseUrl, _setMessageOperationResult); result = HttpHelper.PostData(content, url, _timeout, ht, <strong style="background-color: rgb(255, 0, 0);">"application/json", "text/json"</strong>); return result; }
如果按照紅色的值進行傳遞,那麼伺服器端引數物件就會接收到下圖的說要傳遞的值,
public static string PostData(string request, string url, int timeout, Hashtable ht, string reqType = "application/x-www-form-urlencoded", string resType = "application/json") { string responseString = string.Empty; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.ContentType = reqType;// + ";charset=\"utf-8\"" webRequest.Accept = resType;// resType; webRequest.Method = "POST"; webRequest.Timeout = timeout * 1000; try { foreach (DictionaryEntry de in ht) { webRequest.Headers.Add(de.Key.ToString(), de.Value.ToString()); } byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(request); webRequest.ContentLength = bytes.Length; webRequest.GetRequestStream().Write(bytes, 0, bytes.Length); HttpWebResponse response;//= (HttpWebResponse)webRequest.GetResponse(); try { response = (HttpWebResponse)webRequest.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))) { responseString = reader.ReadToEnd(); } throw new Exception(responseString); } using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))) { responseString = reader.ReadToEnd(); } return responseString; } catch (Exception ex) { throw new Exception(ex.Message); } }