1. 程式人生 > >WebApi傳遞JSON引數 接收不到引數

WebApi傳遞JSON引數 接收不到引數

開發過程中經常進行JSON的傳遞,在WebApi中傳遞JSON字串時,會發現伺服器端接收到不引數值,看下面程式碼

服務端:

public void Post([FromBody]string value)
        {
            LoggerHelper.Info("Post:{0}", value);
        }

客戶端:

複製程式碼
HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("
application/json")); string url = "http://api.oa.com/api/Test/Post"; var json = "{ \"Name\": \"Test\" }"; var httpContent = new StringContent(json, Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var
response = client.PostAsJsonAsync(url, httpContent).Result; if (!response.IsSuccessStatusCode) { Response.Write(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase)); }
複製程式碼

執行客戶端,檢視服務端的日誌,結果為“Post:”,呼叫成功,但引數接收失敗。

查了些資料,顯示WebApi不支援JSON字串做為簡單引數傳遞,既然如此就將JSON字串做為複雜型別進行傳,對程式碼稍做調整,服務端接收JObject引數:

public void Post([FromBody]JObject value)
        {
            
            LoggerHelper.Info("Post:{0}", value.ToString());
        }

客戶端:

複製程式碼
HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string url = "http://api.oa.com/api/Test/Post";

            var json = "{ \"Name\": \"Test\" }";
            var jObject = JObject.Parse(json);
            var response = client.PostAsJsonAsync(url, jObject).Result;
            if (!response.IsSuccessStatusCode)
            {
                Response.Write(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
            }
複製程式碼

執行客戶端,再次檢視服務端的日誌,結果為:

Post:{
"Name": "Test"
},引數傳遞成功