2017-09-26 3 views
1

J'essaie d'obtenir le corps de la requête POST sous la forme string en C#. J'ai écrit ceci:Lecture correcte du corps HttpRequest de manière asynchrone dans l'application Web NetCore

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; 
    } 

Les questions:

  • Le deuxième itération, req.Body.CanRead est true, mais appeler lecture provoque System.ArgumentException
  • Tout est déjà lu sur la première itération. Non seulement cela, System.Text.Encoding.UTF8.GetString ajoute tous les zéros restants du tampon à la chaîne.

Je traiter la demande comme ceci:

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

Répondre

1

Apparemment, il y a une façon plus élégante qui fonctionne aussi:

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

      return content; 
     } 
    }