gpt4 book ai didi

c# - 无法读取输入流

转载 作者:可可西里 更新时间:2023-11-01 08:47:03 24 4
gpt4 key购买 nike

我正在使用 ActionFilterAttribute 在点击 Controller 之前获取请求,如下所示:

 public override void OnActionExecuting(HttpActionContext actionContext)
{
using (var stream = new MemoryStream())
{
HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
}

上面的方法适用于小请求,但对于大的 json,它给了我这个错误:

Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.

并且输入流给出了这个错误

context.Request.InputStream threw an exception of type System.InvalidOperationException System.IO.Stream {System.InvalidOperationException}

我在研究中发现这是超时问题,但我无法更改代码中的超时。我尝试更改 web.config 文件 maxRequestLength="102400000"maxAllowedContentLength="209715100" 中的值,但我仍然面临同样的错误。
如果我读取了 GetBufferedInputStream 但仍然是同样的问题,它只是读取缓冲区的一部分,而不是整个流。

我也试过下面的:

 Stream InStream;
int Len;
InStream = HttpContext.Current.Request.InputStream;
Len = System.Convert.ToInt32(InStream.Length);
byte[] ByteArray = new byte[Len + 1];
InStream.Seek(0, SeekOrigin.Begin);
InStream.Read(ByteArray, 0, Len);
var jsonParam = System.Text.Encoding.UTF8.GetString(ByteArray);

请注意,如果我设置内容类型 application/xmlapplication/x-www-form-urlencoded 它有效,但如果我将其设置为 application/json 它给了我这个错误!!

请指教!

最佳答案

有几点:

首先,如果您尝试从流中读取 0 个字节,则会抛出 System.InvalidOperationException 异常。因此,我将像下面这样更改您的代码并添加对 ContentLength > 0 的检查。

using (var stream = new MemoryStream())
{
HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
if(context.Request.Contentlength > 0)
{
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
}

此外,我曾经遇到过同样的问题并增加了 maxRequestLength在 web.config 中似乎已经解决了这个问题。此链接进一步提供了更多信息 here

关于c# - 无法读取输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52074433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com