gpt4 book ai didi

c# - 如何使用 ReadAsync 将 http 正文变成 dot net core 2.0 中的字符串

转载 作者:太空狗 更新时间:2023-10-29 23:05:16 28 4
gpt4 key购买 nike

我正在接收带有原始正文的 http post 请求,我正在尝试将 http 正文流读入字符串。

我正在使用由 dotnet web 命令生成的基本 Hello World Web 项目。根据documentation :

In the .NET Framework 4 and earlier versions, you have to use methods such as BeginRead and EndRead to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as ReadAsync, WriteAsync, CopyToAsync, and FlushAsync, help you implement asynchronous I/O operations more easily.

所以我尝试使用 ReadAsync方法是这样的:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// _controller = controller;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Run(async (context) =>
{

using (Stream Body = context.Request.Body) {
byte[] result;
result = new byte[context.Request.Body.Length];
await context.Request.Body.ReadAsync(result, 0, (int)context.Request.Body.Length);

String body = System.Text.Encoding.UTF8.GetString(result).TrimEnd('\0');

_log.LogInformation($"Body: {body}");
}
await context.Response.WriteAsync("Hello World!");
});
}

但我收到以下错误:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost1 Request starting HTTP/1.1 POST http://localhost:5000/json/testing?id=2342&name=sas application/json 82 fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HL7ISBH941G6", Request id "0HL7ISBH941G6:00000001": An unhandled exception was thrown by the application. System.NotSupportedException: Specified method is not supported. at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameRequestStream.get_Length() at mtss.ws.Startup.<b__4_0>d.MoveNext() in /home/inspiron/devel/apps/dotnet/mtss-ws/Startup.cs:line 47

-- 更新

我可以将缓冲区的大小设置为 Int16.MaxValue,但这样我就无法读取大于 32k 的正文。

最佳答案

我找到了 this question在 SO 帮助我找到以下解决方案:

app.Run(async (context) =>
{

string body = new StreamReader(context.Request.Body).ReadToEnd();
_log.LogInformation($"Body: {body}");
_log.LogInformation($"Body.Length: {body.Length}");

await context.Response.WriteAsync("Hello World!");
});

异步版本非常相似:

    string body = await new StreamReader(context.Request.Body).ReadToEndAsync();

不确定这是否是最好的方法...

关于c# - 如何使用 ReadAsync 将 http 正文变成 dot net core 2.0 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46022293/

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