讀取 post 請求内容,最友善的就是使用 stream 了(如下),單個 filter 沒問題,但是如果同一個 controller 附加
兩個 filter 就有問題了,第一個 filter 可以正常讀取内容,但是之後的在讀 stream 的長度就是 0 了。
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext context)
{
var task = context.Request.Content.ReadAsStreamAsync();
var content = string.Empty;
using (System.IO.Stream sm = task.Result)
{
if (sm != null)
{
sm.Seek(0, SeekOrigin.Begin);
int len = (int) sm.Length;
byte[] inputByts = new byte[len];
sm.Read(inputByts, 0, len);
sm.Close();
content = Encoding.UTF8.GetString(inputByts);
}
}
}
//讀取post内容
var task = context.Request.Content.ReadAsStreamAsync();
var content = string.Empty;
var sm = task.Result;
sm.Seek(0, SeekOrigin.Begin);//設定流的開始位置
var bytes = sm.ToByteArray();
content = bytes.ToStr();
1.stream 轉 byte[]
/// <summary>
/// Stream Stream 轉換為 byte 數組
/// </summary>
/// <returns></returns>
public static byte[] ToByteArray(this Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 設定目前流的位置為流的開始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
/// <summary>
/// 轉換為 string,使用 Encoding.Default 編碼
/// </summary>
/// <returns></returns>
public static string ToStr(this byte[] arr)
{
return System.Text.Encoding.Default.GetString(arr);
}