Get RawBody from HttpContext of ActionExecutionContext in ASP.NET Core

扶醉桌前 提交于 2020-02-06 07:36:05

问题


I have a base class where I want to include code that is being executed in all of my controller methods. In my special case, I opted for creating a base class, overwriting OnActionExecution, and having my controller classes inherit from that base class. This works quite well:

public class BaseController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        string parsedParameters = string.Empty;
        if (context.ActionArguments.Count > 0)
        {
            inputParameters = JsonConvert.SerializeObject(context.ActionArguments.First().Value,
                                    Formatting.None,
                                    new JsonSerializerSettings
                                    {
                                        NullValueHandling = NullValueHandling.Ignore,
                                    });
        }

        // ...

        base.OnActionExecuting(context);
    }
}

This code takes the mapped view models from the controller method and converts it into JSON (for logging purposes)

Example Controller methods:

public async Task<IActionResult> Create([FromBody]CreateGroupRequest requestModel)

The problem that I currently face is that additional json values that have been passed to the endpoint are not included since they won't be mapped (because such target properties do not exist in the view model)

I want to access the raw body of the Request object. Based on what I've read, it's difficult to access the request body stream if it was already read once. I found multiple solutions on how read the request body stream but they only seem to work for .NET Framework and not .NET Core.

Question: How can I get the full request body (which includes the original JSON posted against the controller) from ActionExecutinContext in ASP.NET Core?


回答1:


You can use EnableBuffering() in .net core 3.x to enable request body for multiple reads :

var bodyStr = "";
var req = context.HttpContext.Request;
req.EnableBuffering();
req.Body.Position = 0;
using (var stream = new StreamReader(req.Body))
{
    bodyStr = stream.ReadToEnd();
}


来源:https://stackoverflow.com/questions/59861461/get-rawbody-from-httpcontext-of-actionexecutioncontext-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!