Access Raw Request Body

后端 未结 4 1405
北恋
北恋 2021-01-04 12:59

I\'m trying to access a request\'s raw input body/stream in ASP.net 5. In the past, I was able to reset the position of the input stream to 0 and read it into a memory strea

4条回答
  •  被撕碎了的回忆
    2021-01-04 13:42

    The implementation of Request.Body depends on the controller action.

    If the action contains parameters it's implemented by Microsoft.AspNet.WebUtilities.FileBufferingReadStream, which supports seeking (Request.Body.CanSeek == true). This type also supports setting the Request.Body.Position.

    However, if your action contains no parameters it's implemented by Microsoft.AspNet.Loader.IIS.FeatureModel.RequestBody, which does not support seeking (Request.Body.CanSeek == false). This means you can not adjust the Position property and you can just start reading the stream.

    This difference probably has to do with the fact that MVC needs to extract the parameters values from the request body, therefore it needs to read the request.

    In your case, your action does not have any parameters. So the Microsoft.AspNet.Loader.IIS.FeatureModel.RequestBody is used, which throws an exception if you try to set the Position property.


    Solution: either do not set the position or check if you actually can set the position first:

    if (Request.Body.CanSeek)
    {
        // Reset the position to zero to read from the beginning.
        Request.Body.Position = 0;
    }
    
    var input = new StreamReader(Request.Body).ReadToEnd();
    

提交回复
热议问题