gpt4 book ai didi

c# - 在 Net Core Web 应用程序中正确异步读取 Http 请求正文

转载 作者:行者123 更新时间:2023-11-30 20:17:03 26 4
gpt4 key购买 nike

我试图在 C# 中将 POST 请求正文作为 string。我写了这个:

    protected async Task<string> readBodyAsync(HttpRequest req)
{
// turns out this is always false...
if(req.Body.CanSeek)
req.Body.Seek(0, SeekOrigin.Begin);
// string buffer
string str = "";
// I wouldn't expect to have to do this in 2017
byte[] buffer = new byte[255];
int offset = 0;
int lastLen = 0;
// On second iteration, CanRead is true but ReadAsync throws System.ArgumentException
while ( req.Body.CanRead && (lastLen = await req.Body.ReadAsync(buffer, offset, buffer.Length))!=0)
{
offset += lastLen;
// This also adds all the \0 characters from the byte buffer, instead of treating like
// normal C string
str += System.Text.Encoding.UTF8.GetString(buffer);
}
// This never executes due to the System.ArgumentException
return str;
}

问题:

  • 在第二次迭代中,req.Body.CanReadtrue,但调用 read 会导致 System.ArgumentException
  • 已经在第一次迭代中读取了所有内容。不仅如此,System.Text.Encoding.UTF8.GetString 将缓冲区中所有剩余的零添加到字符串中。

我这样处理请求:

    app.Run(async (context) =>
{
if(context.Request.Method.ToLower() == "post" && context.Request.Path.ToString().EndsWith("/ajax"))
{
string requestText = await readBodyAsync(context.Request);
/// Parsing of the JSON in requestText should be here
// but I can't get that text
await context.Response.WriteAsync("{data: \"AJAX TEST\"}");
}
else
{
await context.Response.WriteAsync("Hello World! And go away. Invalid request.");
}
});

最佳答案

    private async Task<string> StreamToStringAsync(HttpRequest request)
{
using (var sr = new StreamReader(request.Body))
{
return await sr.ReadToEndAsync();
}
}

关于c# - 在 Net Core Web 应用程序中正确异步读取 Http 请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46430272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com