Post推送過來的數據流獲取后部分中文出現亂碼,晚上找了好多辦法,不如朋友鼎力相助,哈哈哈~不說廢話了上代碼把
舊代碼基本是網上普遍寫法,字段不長用起來不會有亂碼情況,但是傳送字段一旦過長,超過byte的1024個字節后,中文部分的兩個字節恰好卡到這個位置就容易出現 "??"或者其他情況.
原代碼:
System.IO.Stream s = HttpContext.Request.InputStream;
if (s == null)
{
return Json(ReplyJson.ReplyMes(ErrorEnum.error, new Dictionary<string, object>() { { "msg", "推送json數據為空" } }), JsonRequestBehavior.AllowGet);
}
int count = 0;
byte[] buffer = new byte[s.Length];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, 1024)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
s.Flush();
s.Close();
s.Dispose();
新代碼:
#region 數據流獲取
StringBuilder builder = new StringBuilder();
using (MemoryStream ms = new MemoryStream())
{
//copy以進行后續讀取,否則InputStream將被釋放,不能操作第二次
HttpContext.Request.InputStream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
{
builder.Append(sr.ReadToEnd());
}
}
if (string.IsNullOrEmpty(builder.ToString()))
{
return Json(ReplyJson.ReplyMes(ErrorEnum.error, new Dictionary<string, object>() { { "msg", "推送json數據為空" } }), JsonRequestBehavior.AllowGet);
}
#endregion
目前這樣處理,有其他問題再說