【问题标题】:How to get the http body into a String in dot net core 2.0 using ReadAsync如何使用 ReadAsync 将 http 正文转换为 dot net core 2.0 中的字符串
【发布时间】:2018-02-11 19:41:42
【问题描述】:

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

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

在 .NET Framework 4 及更早的版本中,必须使用方法 比如 BeginRead 和 EndRead 来实现异步 I/O 操作。这些方法在 .NET Framework 中仍然可用 4.5 支持遗留代码;但是,新的异步方法,例如 ReadAsync、WriteAsync、CopyToAsync 和 FlushAsync,可以帮助您实现 异步 I/O 操作更容易。

所以我尝试了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!");
    });
}

但我收到以下错误:

信息:Microsoft.AspNetCore.Hosting.Internal.WebHost1 请求开始 HTTP/1.1 POST http://localhost:5000/json/testing?id=2342&name=sas application/json 82 失败:Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HL7ISBH941G6", Request id "0HL7ISBH941G6:00000001": 一个未处理的异常被抛出 应用。 System.NotSupportedException:指定的方法不是 支持的。在 Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameRequestStream.get_Length() 在 mtss.ws.Startup.d.MoveNext() 中 /home/inspiron/devel/apps/dotnet/mtss-ws/Startup.cs:47行

--更新

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

【问题讨论】:

  • 您能否向我们展示整个代码,首先您是如何获取数据的?
  • 没问题,给你

标签: c# asp.net-core stream .net-core .net-core-2.0


【解决方案1】:

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

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();

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

【讨论】:

    【解决方案2】:

    我也遇到了 ReadAsync 无法获得完整内容的问题。我的解决方案类似于opensas 提供的解决方案,但是,我使用“使用”来完成它,因此会自动调用 StreamReader 的 dispose 方法。我还在 StreamReader 中添加了 UTF8 编码选项。

    using StreamReader reader = new StreamReader (Request.Body, Encoding.UTF8);
    string body = await reader.ReadToEndAsync ();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2010-12-15
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多