2017-09-03 1 views
2

Je reçois et http post demande, avec le corps brut, et j'essaie de lire le corps http Stream dans une chaîne.Comment faire pour obtenir le corps http dans une chaîne en dot net core 2.0 en utilisant ReadAsync

J'utilise le projet Web de base Hello World généré par la commande dotnet web. Selon le 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.

J'ai donc essayé la méthode ReadAsync avec quelque chose comme ceci:

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!"); 
    }); 
} 

Mais je reçois l'erreur suivante:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost 1 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

- mise à jour

Je pourrais obtenir quelque chose de travail en réglant la taille du tampon à Int16.MaxValue, mais de cette façon je ne peux pas lire les corps plus grands que 32k.

+0

Pouvez-vous nous montrer le code entier, comment vous obtenez les données en premier lieu? –

+0

bien sûr, voilà – opensas

Répondre

1

Je trouve this question à SO qui a aidé ma trouver la solution suivante:

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!"); 
}); 

et la version async est à peu près semblables:

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

Je ne sais pas si cela est la meilleure façon de le faire il ...