简体   繁体   English

VB.NET InputStream为空

[英]VB.NET InputStream is empty

I'm using .NET 4.0 and am attempting to get the Request.InputStream into a string. 我正在使用.NET 4.0,并尝试将Request.InputStream转换为字符串。 I've tried the obvious: 我尝试了明显的方法:

Dim req As HttpRequest = HttpContext.Current.Request
' Log input stream length
util.SystemError("inputstream length = " + req.InputStream.Length.ToString, "MBOL")
req.InputStream.Position = 0
Dim encodedString As String = New StreamReader(req.InputStream).ReadToEnd()

This shows me the inputstream length is 1671, but the encodedString I get is empty. 这告诉我inputstream的长度是1671,但是我得到的encodeString是空的。 I've added a try / catch around it, but it doesn't seem to error, it just returns an empty string. 我添加了一个try / catch,但是似乎没有错误,它只是返回一个空字符串。

Any ideas where this could be going wrong? 有什么想法可能会出错吗? Thanks in advance for any assistance with this. 在此先感谢您的协助。

An input stream cannot be necessarily be read several times, it's by contract read-once (though specific implementations may relax this restriction). 输入流不一定必须多次读取,而是按合同一次读取 (尽管特定实现可能会放宽此限制)。

As a consequence, you cannot take its length since that actually reads the stream. 结果,您不能取其长度,因为它实际上是读取流的。 Even resetting its position to 0 isn't guaranteed to work (and doesn't, as you can see). 即使将其位置重置为0也不能保证正常工作(如您所见,也不可行)。

If you want to get the length of the content before reading it, you need to rely on the Content-Length header field. 如果要读取内容之前获取内容的长度,则需要依赖Content-Length标头字段。 Note that the server doesn't have to provide this. 请注意,服务器不必提供此功能。 The only 100% reliable way of getting the content length is to read the content, then get its length. 获取内容长度的唯一100%可靠的方法是读取内容, 然后获取其长度。

It could be argued that the Stream base class shouldn't have a Length property at all. 可以说Stream基类根本不应该具有Length属性。 It's a weak design. 这是一个较弱的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM