【问题标题】:Api MemoryStream c# , how this code works?Api MemoryStream c# ,这段代码是如何工作的?
【发布时间】:2016-10-03 11:15:36
【问题描述】:

我在这里有一个问题,我知道这对你来说很简单,但实际上我需要逐行了解它的作用..

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);
}

【问题讨论】:

  • 此代码假定传入的 HTTP 请求具有 Utf8 编码的正文并将其复制到字符串中。不过,这个答案对你没有帮助。阅读How to Ask 并解释您要解决的问题。
  • 很抱歉问了这样的问题,我不是故意浪费你的时间。谢谢你的帮助编解码器
  • @CodeCaster 它做得很糟糕;调用stream.ToArray()(除非您知道长度是可管理的,并且您对分配没问题)不是这样做的好方法;同样,无需具体化字符串来查找长度 - Encoding/Encoder 具有更有效地做到这一点的机制

标签: c# stream httprequest


【解决方案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);
}

请注意,实际上这里的所有事情都可以更有效地完成。这不是很好的示例代码。

【讨论】:

  • 感谢您抽出宝贵时间!我知道这是一个愚蠢的问题,但非常感谢!
猜你喜欢
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 2011-05-16
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多