WebAPI传递大数据
在接口中传输图片进制流或BASE64字符串时,使用FormUrlEncodedContent处理参数时,可能会因为参数太长导致异常无效的URL:URL字符串太长
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public async Task<string> Post(string url, Dictionary<string, string> param) { string result=""; HttpClient click = new HttpClient(); HttpContent postContent = new FormUrlEncodedContent(param); try { var respMsg = await click.PostAsync(url, postContent); respMsg.EnsureSuccessStatusCode(); result = await respMsg.Content.ReadAsStringAsync(); } catch (HttpRequestException ex) { result = ex.Message; } return result; }
|
可是当param太大时 new FormUrlEncodedContent(param)就会抛出异常无效的URL:URL字符串太长
可以换一种方式实现 StringContent!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public async Task<string> Post(string url, Dictionary<string, string> param) { string result=""; HttpClient click = new HttpClient(); var urlcode = HttpHelp.DicToFormCode(param); //需要把键值对转为urlencoded StringContent postContent = new StringContent(urlcode, Encoding.UTF8, "application/x-www-form-urlencoded"); try { var respMsg = await click.PostAsync(url, postContent); respMsg.EnsureSuccessStatusCode(); result = await respMsg.Content.ReadAsStringAsync(); } catch (HttpRequestException ex) { result = ex.Message; } return result; }
static string DicToFormCode(Dictionary<string, string> param) { string pc = "";
foreach (var p in param) { pc += HttpUtility.UrlEncode(p.Key); if (p.Value.GetType() == typeof(object[])) pc += "=" + HttpUtility.UrlEncode(JsonConvert.SerializeObject(p.Value)) + "&"; else pc += "=" + HttpUtility.UrlEncode(p.Value.ToString()) + "&"; } pc = pc.TrimEnd('&');
return pc; }
|