开发过程中经常进行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"
},参数传递成功