c# - HttpContext.Response.Body.Position = 0 - "Specified method is not supported"错误

标签 c# httpresponse httpcontext

我设置了一些日志记录中间件,可以使用 HttpContext 获取和记录信息。

我需要将 HttpResponse.Body 的位置设置为 0 才能读取整个流,但是,无论我尝试什么,它都会抛出“不支持指定的方法”并失败。

这对我来说很奇怪,因为 position 是内置在 HttpResponse.Body 中的,我之前成功地使用过它。

我也尝试使用 HttpResponse.Body.Seek 得到相同的结果。

此时我被卡住了,任何帮助将不胜感激。

更新:一旦我将它移动到一个新的内存流中,我就能够改变 response.body 的位置,但是,现在它返回一个空的 body。

public async Task Invoke(HttpContext context)
        {
            //Retrieve request & response
            var request = context.Request;
            var response = context.Response;

            if (request.Path != "/")
            {
                var reqBody = request.Body;
                var resBody = response.Body;
                string path = request.Path;
                string method = request.Method;
                string queryString = HttpUtility.UrlDecode(request.QueryString.ToString());
                int statusCode = context.Response.StatusCode;

                var buffer = new byte[Convert.ToInt32(request.ContentLength)];
                await request.Body.ReadAsync(buffer, 0, buffer.Length);
                var reqBodyText = Encoding.UTF8.GetString(buffer);
                request.Body = reqBody;

                var responseBodyStream = new MemoryStream();
                context.Response.Body = responseBodyStream;

                await _next(context);

                responseBodyStream.Seek(0, SeekOrigin.Begin);
                var resBodyText = new StreamReader(responseBodyStream).ReadToEnd();
                responseBodyStream.Seek(0, SeekOrigin.Begin);
                await responseBodyStream.CopyToAsync(context.Response.Body);

                ...
            }
        }

最佳答案

根据解决此问题的评论 GitHub issue ,您需要启用缓冲

为此,将以下代码片段添加到您的 Startup.cs Configure 方法中:

app.Use(async (context, next) =>
{
    context.Request.EnableBuffering();
    await next();
});

关于c# - HttpContext.Response.Body.Position = 0 - "Specified method is not supported"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161654/

相关文章:

c# - 如何在 SQL Server CE 数据库 windows phone 8 上使用双向绑定(bind)

c# - 如何创建通用 Task.ContinueWith 扩展方法

c# - 数据库设计 : Custom fee/billing charge rates

php - 如何使用 CakePHP 3.4 输出自定义 HTTP 正文内容?回显导致 "Unable to emit headers"错误

c# - IHttpContextAccessor.HttpContext.User.Identity 显示 CurrentUserService 服务中的所有空属性

C# - 委托(delegate) Predicate<T>

jQuery - 获取 AJAX 响应 header

wcf - HttpContext.Current在我的Web服务中为null

asp.net - GetHashCode 只是 cargo 崇拜吗?

javascript - 从 api 请求获取所有响应 header 。目前并非全部可用