在.net core中绑定原始请求体而不读取请求流

sky*_*yrd 1 .net c# asp.net-web-api .net-core asp.net-core

我们的一位客户坚持向我们的 API 发送原始请求正文(不是 json 或 xml),并且由于 .net core 默认情况下不支持它,所以我使用了类似的想法,如下所示:

[HttpPost]
[Route("example/{path}")]
public async Task<string> ReadStringDataManual(string path)
{
    using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
    {  
        return await reader.ReadToEndAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,在生产中我们意识到 API 在加载时会抛出以下异常。

System.Runtime.CompilerServices.TaskAwaiter:UnsafeOnCompletedInternal (method time = 1 ms, total time = 1 ms)
undefined(2011ms): await continuation

Run Code Online (Sandbox Code Playgroud)

我不确定它是否与 Kestrel 相关,但我相信这是因为大量的 I/O 操作。我还尝试了一种天真的方法 - 将带有[FromBody]属性的参数添加到方法签名中,但没有运气。

是否有其他选项可以在不使用流读取器的情况下读取原始请求正文?

谢谢。

TiG*_*reX 5

读取请求正文.NetCore有点不同

[HttpPost]
[Route("example/{path}")]
public async Task<string> ReadStringDataManual(string path)
{

    ReadResult requestBodyInBytes = await Request.BodyReader.ReadAsync();
    Request.BodyReader.AdvanceTo(requestBodyInBytes.Buffer.Start, requestBodyInBytes.Buffer.End);
    string body = Encoding.UTF8.GetString(requestBodyInBytes.Buffer.FirstSpan);

    //Rest of the code

    return body;
}
Run Code Online (Sandbox Code Playgroud)