本文主要是介绍asp.net 引用webapi接收返回的Json类型数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在网上查到了一些例子加上自己的一些修改,改写了这个方法
private async Task<string> InvokeWebapi(string strurl, string strapi, string strtype, string strJson){HttpClient client = new HttpClient();//client.DefaultRequestHeaders.Add("","");client.BaseAddress = new Uri(strurl);client.Timeout = TimeSpan.FromSeconds(510);string result = "";if (strtype.ToLower() == "post"){// var content = new FormUrlEncodedContent(dics);var content = new StringContent(strJson);content.Headers.ContentType = new MediaTypeHeaderValue("application/json");content.Headers.ContentLength = (Encoding.UTF8.GetBytes(strJson)).Length;HttpResponseMessage response = client.PostAsync(strapi, content).Result;if (response.IsSuccessStatusCode){result = await response.Content.ReadAsStringAsync();}}else if (strtype.ToLower() == "get"){HttpResponseMessage response = client.GetAsync(strapi).Result;if (response.IsSuccessStatusCode){result = await response.Content.ReadAsStringAsync();}}//对结果处理JObject jo = new JObject();jo = (JObject)JsonConvert.DeserializeObject(result);var nRet = jo.ToString();//如果要解析里面的某个实体对象:((JObject)jo["data"]).toString();//data是对应的字段名称return nRet;}/// <summary>/// 解析JSON字符串生成对象实体/// </summary>/// <typeparam name="T">对象类型</typeparam>/// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>/// <returns>对象实体</returns>public static T DeserializeJsonToObject<T>(string json) where T : class{try{JsonSerializer serializer = new JsonSerializer();StringReader sr = new StringReader(json);object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));T t = o as T;return t;}catch (Exception){return null;}}
调用如下
string sJson = JsonConvert.SerializeObject(new { id, name});//api传入是json字符串string strResult= InvokeWebapi("网址", "网站/api/控制器名称", "POST", sJson).Wait();api = DeserializeJsonToObject<ApiResult>(strResult);//api是实体类
这篇关于asp.net 引用webapi接收返回的Json类型数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!