getting the request body inside HttpContext from a Middleware in asp.net core 2.0

前端 未结 4 1749
礼貌的吻别
礼貌的吻别 2021-02-20 10:45

I am having a simple middleware which fetches the body of the request and store it in a string. It is reading fine the stream, but the issue is it wont call my controller which

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-20 11:05

    You need to convert HttpContext.Request.Body from a forward only memory stream to a seekable stream, shown below.

    //  Enable seeking
    context.Request.EnableBuffering();
    //  Read the stream as text
    var bodyAsText = await new System.IO.StreamReader(context.Request.Body).ReadToEndAsync();
    //  Set the position of the stream to 0 to enable rereading
    context.Request.Body.Position = 0; 
    

提交回复
热议问题