1、get或者POST传输一个小于255字节方式
传递小型数据量的信息到服务端去获取服务器信息的方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 服务端源获取信息 /// </summary> /// <param name="strUrl">服务URL</param> /// <param name="objParemeters">参数列表(实体型)</param> /// <param name="ticike">身份号</param> /// <returns>返回结果实体</returns> public static T JsonRequestToObject<T>(string strUrl, Object objParemeters, string ticike) { try { Postinfo postinfo = new Postinfo(); postinfo.ticike = ticike; postinfo.content = JsonConvert.SerializeObject(objParemeters); postinfo.Client = "PcClient"; string param = JsonConvert.SerializeObject(postinfo); using (var client = new HttpClient()) { var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"", param}//键名必须为空 }); var result = client.PostAsync(strUrl, content).Result.Content.ReadAsStringAsync().Result; T ds = JsonConvert.DeserializeObject<T>(result); return ds; } } catch (Exception ex) { //Log.Writer(ex.Message + ":" + ex.StackTrace); LogHelper.WriteLog(typeof(T), ex.StackTrace); object obj = Activator.CreateInstance(typeof(T)); return (T)obj; } }
因为WebAPi传递信息需要一个特殊的FromBody来接收,需要用个类型来包信息后webapi才能获取到传递来的信息
var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"", param}//键名必须为空 });
WebApi定义的接受方式
[HttpPost] public HttpResponseMessage UserLogin([FromBody]string postinfo) { //逻辑代码 XXXXXXXXXX }
[FromBody]获取到的信息类型为一个string
2、POS传输一个大于255字节方式
当你需要传递个大型数据时(例如分片上传文件时)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 像服务器传输一个超过255字节的大数据,服务端源获取返回一个实体 /// </summary> /// <param name="strUrl">服务URL</param> /// <param name="objParemeters">参数列表(实体型)</param> /// <param name="ticike">身份号</param> /// <returns>返回结果实体</returns> public static T JsonRequestServiceToObject<T>(string strUrl, Object objParemeters, string ticike) { try { Postinfo postinfo = new Postinfo(); postinfo.ticike = ticike; postinfo.content = JsonConvert.SerializeObject(objParemeters); postinfo.Client = "PcClient"; string param = JsonConvert.SerializeObject(postinfo); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var httpContent = new StringContent(param, Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = client.PostAsync(strUrl, httpContent).Result.Content.ReadAsStringAsync().Result; T ds = JsonConvert.DeserializeObject<T>(result); return ds; } } catch (Exception ex) { LogHelper.WriteLog(typeof(T), ex); object obj = Activator.CreateInstance(typeof(T)); return (T)obj; } }
改变的是包住信息的类型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var httpContent = new StringContent(param, Encoding.UTF8);
webApi获取的信息的方式改为用个定义的类来获取
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[HttpPost] public HttpResponseMessage PostUploadFile([FromBody]Postinfo postinfo) { //逻辑代码 XXXXXXXXX }