Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试使用流i get System.InvalidOperationException(readtimeout、writetimeout属性)读取请求正文_C#_Asp.net_.net_Asp.net Web Api - Fatal编程技术网

C# 尝试使用流i get System.InvalidOperationException(readtimeout、writetimeout属性)读取请求正文

C# 尝试使用流i get System.InvalidOperationException(readtimeout、writetimeout属性)读取请求正文,c#,asp.net,.net,asp.net-web-api,C#,Asp.net,.net,Asp.net Web Api,我试图从HttpActionExecutedContext上下文读取请求正文,因为我想记录异常(.net framework)。 在一些帖子中,解决方案是一种类似 private string GetBodyFromRequest(HttpActionExecutedContext context) { string data; using (var stream = context.Request.Content.ReadAsSt

我试图从HttpActionExecutedContext上下文读取请求正文,因为我想记录异常(.net framework)。 在一些帖子中,解决方案是一种类似

private string GetBodyFromRequest(HttpActionExecutedContext context)
        {
            string data;
            using (var stream = context.Request.Content.ReadAsStreamAsync().Result)
            {
                if (stream.CanSeek)
                {
                    stream.Position = 0;
                }
                data = context.Request.Content.ReadAsStringAsync().Result;
            }
            return data;
        }
或者

private async Task<string> GetBodyAsync(HttpActionExecutedContext context)
        {
            string request;
            using (var memoryStream = new MemoryStream())
            {
                var requestStream = await context.Request.Content.ReadAsStreamAsync();
                requestStream.Position = 0;
                requestStream.CopyTo(memoryStream);
                memoryStream.Position = 0;
                using (StreamReader streamReader = new StreamReader(memoryStream))
                {
                    request = streamReader.ReadToEnd();
                }
            }
            return request;
        }

我有System.InvalidOperationException

读取超时

,

写出来


属性,但不抛出停止程序的异常,只返回空字符串。

您不必通过调用
Result
来阻止
async
操作。Result但在第二个实现中,var memoryStream=new memoryStream()行中存在相同的问题
using (var stream = context.Request.Content.ReadAsStreamAsync().Result)
using (var memoryStream = new MemoryStream())