2016-10-03 59 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

感谢您花时间!我知道这是一个虚假的问题,但我非常感谢! –