问题
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