/// <summary> /// 遍历所有参数 /// </summary> /// <param name="request"> 请求 </param> /// <param name="bodyParams"> body参数 </param> private void FindParams(IHttpRequest request, out List <KeyValuePair <string, object> > bodyParams) { bodyParams = new List <KeyValuePair <string, object> >(); foreach (var param in request) { var name = param.Name; var value = param.Value; switch (param.Location) { case HttpParamLocation.Auto: if (Url.Contains("{" + name + "}")) { goto case HttpParamLocation.Path; } if (request.Method == HttpRequestMethod.Get) { goto case HttpParamLocation.Query; } goto case HttpParamLocation.Body; case HttpParamLocation.Query: Request?.OnQueryParamFound(ref name, ref value); if ((name != null) || (value != null)) { _UrlEncodedBuilder.AppendObject(name, value); } break; case HttpParamLocation.Body: request.OnBodyParamFound(ref name, ref value); if ((name != null) || (value != null)) { bodyParams.Add(new KeyValuePair <string, object>(name, value)); } break; case HttpParamLocation.Path: AddPathParam(name, value); break; case HttpParamLocation.Header: AddHeader(name, param.Values.Select(it => it.ToString())); break; default: throw new ArgumentOutOfRangeException(nameof(param.Location)); } } }
/// <summary> /// 将正文格式化为字节流 /// </summary> /// <param name="format"> 包含格式规范的格式字符串 </param> /// <param name="body"> 请求或响应正文 </param> /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param> /// <returns> </returns> public override byte[] Serialize(string format, IEnumerable <KeyValuePair <string, object> > body, IFormatProvider formatProvider) { if (_UrlEncodedBuilder == null) { _UrlEncodedBuilder = new HttpUrlEncodedBuilder(); } else { _UrlEncodedBuilder.Clear(null); } var request = formatProvider.GetFormat(typeof(IHttpRequest)) as IHttpRequest; _UrlEncodedBuilder.ArrayEncodeMode = request?.Query.ArrayEncodeMode ?? ArrayEncodeMode.Default; _UrlEncodedBuilder.ObjectEncodeMode = request?.Query.ObjectEncodeMode ?? ObjectEncodeMode.Default; foreach (var item in body) { _UrlEncodedBuilder.AppendObject(item.Key, item.Value); } var encoding = GetEncoding(formatProvider) ?? Encoding.ASCII; return(encoding.GetBytes(_UrlEncodedBuilder.ToString())); }