As the title, is it possible to get the request parameter?
I try to get it from request body, but failed, the task.Result is zero. it seems the request body is empty.
Anyone can help me, it would be much appreciated.
The code as below:
public class LogFilter : Attribute, IActionFilter
{
private ILogger<LogFilter> _logger;
private ITestAService _service;
public LogFilter(ILogger<LogFilter> logger, ITestAService service)
{
_logger = logger;
_service = service;
}
public void OnActionExecuted(ActionExecutedContext context)
{
var content = new StringBuilder();
using (Stream sm = context.HttpContext.Request.Body)
{
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
var task = sm.ReadAsync(buffer, 0, 1024);
if (task.Result > 0)
{
content.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
}
}
}
Request Body is consumed and not available in the OnActionExecuted, I do it like this,
Read The Request Body and Store it HTTPContext
public void OnActionExecuting(ActionExecutingContext context)
{
try
{
var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
var requestBody = FormatRequestBody(context.ActionArguments);
context.HttpContext.Items["LogRequestBody"] = requestBody;
}
}
catch (Exception ex)
{
_logger.Error("Error in LogServiceCallFilter", ex);
}
}
public string FormatRequestBody(IDictionary<string, object> actionArguments)
{
try
{
if (actionArguments != null)
return $"{JsonConvert.SerializeObject(actionArguments)}";
}
catch (Exception ex)
{
_logger.Error("Error in LogServiceCallFilter", ex);
}
return "";
}
Read the Request Body you already stored in HttpContext
public void OnActionExecuted(ActionExecutedContext context)
{
try
{
var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
var actionName = context.ActionDescriptor.RouteValues["controller"] + "/" + context.ActionDescriptor.RouteValues["action"];
var requestBody = context.HttpContext.Items["LogRequestBody"] != null ? context.HttpContext.Items["LogRequestBody"].ToString() : "";
context.HttpContext.Items.Remove("LogRequestBody");
}
}
catch (Exception ex)
{
_logger.Error("Error in LogServiceCallFilter", ex);
}
}