C# 尝试使用流i get System.InvalidOperationException(readtimeout、writetimeout属性)读取请求正文
我试图从HttpActionExecutedContext上下文读取请求正文,因为我想记录异常(.net framework)。 在一些帖子中,解决方案是一种类似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
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())