2016-10-03 61 views
-2

我在這裏有一個問題,我知道這是簡單的對你,但實際上我需要了解它做什麼,一行行..Api MemoryStream c#,這個代碼是如何工作的?

using (var stream = new MemoryStream()) 
{ 
    var context = (System.Web.HttpContextBase)Request.Properties["MS_HttpContext"]; 
    context.Request.InputStream.Seek(0, SeekOrigin.Begin); 
    context.Request.InputStream.CopyTo(stream); 
    strContent = Encoding.UTF8.GetString(stream.ToArray()); 
    AppLog.Write("Request content length: " + strContent.Length); 
} 
+3

此代碼假定傳入的HTTP請求具有Utf8編碼的正文並將其複製到字符串中。這個答案不會幫助你。閱讀[問]並解釋你想要解決的問題。 – CodeCaster

+0

抱歉,問這樣的事情,我不是故意浪費你的時間..感謝你的幫助codecaster –

+1

@CodeCaster和它做得很糟糕;調用'stream.ToArray()'(除非你知道長度是可管理的,並且你可以使用這個分配)並不是一個好的方法;同樣,沒有必要實現一個字符串來查找長度 - 「編碼」/「編碼器」有更高效的機制 –

回答

1
// create a MemoryStream to act as a buffer for some unspecified data 
using (var stream = new MemoryStream()) 
{ 
    // obtain the http-context (not sure this is a good way to do it) 
    var context = (System.Web.HttpContextBase)Request.Properties["MS_HttpContext"]; 
    // reset the context's input stream to the start 
    context.Request.InputStream.Seek(0, SeekOrigin.Begin); 
    // copy the input stream to the buffer we allocated before 
    context.Request.InputStream.CopyTo(stream); 
    // create an array from the buffer, then use that array to 
    // create a string via the UTF8 encoding 
    strContent = Encoding.UTF8.GetString(stream.ToArray()); 
    // write the number of characters in the string to the log 
    AppLog.Write("Request content length: " + strContent.Length); 
} 

注意,實際上這裏的一切都可以做更高效。這不是很好的示例代碼。

+0

感謝您花時間!我知道這是一個虛假的問題,但我非常感謝! –