/// <summary>
/// 发送指定的 form data 数据。
/// </summary>
/// <param name="request">WebRequest 扩展实例</param>
/// <param name="data">提交数据时所需要的数据。可使用 <code>new { name = "xxx" }</code> 匿名对象的形式提供。</param>
/// <param name="encoding">对于提交的数据的编码格式。null表示使用默认的 UTF-8 编码格式。</param>
/// <returns>当前 <see cref="WebRequest"/> 实例。</returns>
/// <exception cref="System.ArgumentNullException">data</exception>
public static async Task <WebResponse> PushDataAsync(this WebRequest request, object data, Encoding encoding = null)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
var form_data = string.Empty;
if (data.GetType() != typeof(string))
{
var properties = new Dictionary <string, string>();
foreach (var propInfo in data.GetType().GetRuntimeProperties())
{
properties.Add(propInfo.Name, propInfo.GetValue(data).ToString());
}
form_data = properties.Select(kvp => $"{kvp.Key}={kvp.Value}").Aggregate((prev, next) => $"{prev}&{next}");
}
else
{
form_data = data.ToString();
}
var buffer = form_data.ToBytes(encoding);
using (var stream = await request.GetRequestStreamAsync())
{
stream.Write(buffer, 0, buffer.Length);
}
return(await request.GetResponseAsync());
}