简体   繁体   English

HttpContext.Response.Body.Position = 0 - “不支持指定的方法”错误

[英]HttpContext.Response.Body.Position = 0 - "Specified method is not supported" error

I've got some logging middleware I've setup that grabs and logs information utilizing HttpContext.我已经设置了一些日志记录中间件,它们使用 HttpContext 获取和记录信息。

I need to set the position of the HttpResponse.Body to 0 in order to read the whole stream, however, no matter what I try, it throws "Specified method is not supported" and fails.我需要将 HttpResponse.Body 的位置设置为 0 以读取整个流,但是,无论我尝试什么,它都会抛出“不支持指定的方法”并失败。

This is very weird to me because position is built right into HttpResponse.Body and I've used it before successfully.这对我来说很奇怪,因为 position 内置于 HttpResponse.Body 中,我之前成功使用过它。

I also tried to use HttpResponse.Body.Seek with the same result.我还尝试使用 HttpResponse.Body.Seek 获得相同的结果。

At this point I'm stuck, any help would be appreciated.在这一点上我被卡住了,任何帮助将不胜感激。

UPDATE: I was able to get the response.body position to change once I moved it into a new memory stream, however, now it returns an empty body back.更新:一旦我将 response.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);

                ...
            }
        }

I was able to solve this:我能够解决这个问题:

Firstly, I set the response to its own memory stream and call await _next(context) after the stream was set:首先,我将响应设置为它自己的内存流并在设置流后调用 await _next(context) :

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

await _next(context);

Then once I did this, I noticed I was getting an empty body back, this was due to trying to set an empty body back as the response context:然后一旦我这样做了,我注意到我得到了一个空的身体,这是由于试图将一个空的身体设置回作为响应上下文:

await responseBodyStream.CopyToAsync(context.Response.Body);

I removed this line and everything started working correctly.我删除了这一行,一切都开始正常工作。

I was facing this issue in my Asp.Net core API today.我今天在我的 Asp.Net 核心 API 中遇到了这个问题。

在此处输入图片说明

The issue was, I forgot to add the [FromBody] parameter to my API.问题是,我忘记将[FromBody]参数添加到我的 API 中。 After adding the same as below, the issue was resolved.添加如下相同内容后,问题解决。

[HttpPost("merkliste/create")]
public virtual async Task<IActionResult> MerklisteWorksheetCreate(string worksheetName, [FromBody] string elementDetailsArray)

在此处输入图片说明

Hope it helps.希望能帮助到你。

You are probably accesing the response body before it is ready.您可能在响应主体准备好之前访问它。 Postpone the execution of the Task Invoke(HttpContext context) to a more later step( when it is ready) in the execution pipeline将 Task Invoke(HttpContext context) 的执行推迟到执行管道中更晚的步骤(当它准备好时)

As per the comment that solved this GitHub issue , you need to enable buffering .根据解决此GitHub 问题的评论,您需要启用缓冲

To do so, add the following snippet to your Startup.cs Configure method:为此,请将以下代码段添加到您的Startup.cs Configure方法中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM