How do I get the raw request body from the Request.Content object using .net 4 api endpoint

后端 未结 4 1474
北海茫月
北海茫月 2020-12-09 15:02

I\'m trying to capture the raw request data for accountability and want to pull the request body content out of the Request object.

I\'ve seen suggestions doing a Re

4条回答
  •  无人及你
    2020-12-09 15:42

    For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

    [HttpPut("{pathId}/{subPathId}"),
    public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
    {
    
        var body = new StreamReader(Request.Body);
        //The modelbinder has already read the stream and need to reset the stream index
        body.BaseStream.Seek(0, SeekOrigin.Begin); 
        var requestBody = body.ReadToEnd();
        //etc, we use this for an audit trail
    }
    

提交回复
热议问题