HttpContent提供了ReadAsFormDataAsync()方法,实际开发中的拦截器、等常常产生重置Request流的需求,自定义解析方法如下,测试效率还算不错,字符串分切比原生读取快,自定义方法是线性时间算法,进一步提高的了效率。
public static NameValueCollection FormResolveCustom(String reqStr) { NameValueCollection form = new NameValueCollection(8); Char[] split = { '=' }; String[] forms = reqStr.Split('&'); for (Int32 i = 0; i < forms.Length; i++) { String[] kvp = forms[i].Split(split, 2, StringSplitOptions.RemoveEmptyEntries); if (kvp.Length == 2) { form.Add(kvp[0], HttpUtility.UrlDecode(kvp[1])); } else if (kvp.Length == 1) { form.Add(kvp[0], null); } } return form; } public static NameValueCollection FormResolvePro(String reqStr) { NameValueCollection form = new NameValueCollection(8); Int32 eq = 0; Int32 at = 0; for (Int32 i = 0; i < reqStr.Length; i++) { if (reqStr[i] == '=') { at = i; } else if (reqStr[i] == '&' || i == reqStr.Length - 1) { Int32 valueLength = i - at - 1; if (i == reqStr.Length - 1) { valueLength++; } if (at > eq && valueLength > 0) { String name = HttpUtility.UrlDecode(reqStr.Substring(eq, at - eq)); String value = HttpUtility.UrlDecode(reqStr.Substring(at + 1, valueLength)); if (!String.IsNullOrWhiteSpace(name)) { form.Add(name, value); } } eq = i + 1; at = i + 1; } } return form; }