Use*_*291 11 c# memorystream inputstream asp.net-web-api2
我ActionFilterAttribute在按下控制器之前用来获取请求,如下所示:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
上面的方法适用于小的请求但是对于一个大的json,它给了我这个错误:
在HttpRequest.GetBufferedInputStream的调用者填充内部存储之前,访问了BinaryRead,Form,Files或InputStream.
输入流会出现此错误
context.Request.InputStream引发了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);
Run Code Online (Sandbox Code Playgroud)
请注意,如果我设置内容类型application/xml或application/x-www-form-urlencoded它的工作原理,但是如果我将其设置为application/json它会给我这个错误!!
请指教!
这就是我在模型绑定器中执行此操作的方法,但我不确定它将如何与您的操作过滤器一起使用。我上网查了一下,信息有矛盾;有人说您无法读取输入流,因为它不可查找,并且 ASP.NET 需要读取它才能绑定模型。有人说确实可以查找,就用上面分享的方法吧。因此,找出真正有效的唯一方法就是进行测试。
我希望我的代码示例可以帮助您解决这个问题。
object request = null;
if (actionContext.Request.Method == HttpMethod.Post && "application/json".Equals(actionContext.Request.Content.Headers.ContentType.MediaType))
{
var jsonContentTask = actionContext.Request.Content.ReadAsStringAsync();
Task.WaitAll(jsonContentTask);
string jsonContent = jsonContentTask.Result;
//... other stuff
}
Run Code Online (Sandbox Code Playgroud)