Is there any way to get request body in .NET Core FilterAttribute?

后端 未结 4 1519
暗喜
暗喜 2021-02-08 23:26

Sample of my request

http://localhost:8065/api/note
POST
content-type:application/json
request body: { \"id\" : \"1234\", \"title\" : \"test\", \"status\" : \"dr         


        
4条回答
  •  有刺的猬
    2021-02-08 23:53

    Following snippet worked for me, to log request only if there is any exception.(.Net Core 3.1)

    {

    public class ExceptionFilter : IActionFilter
    {
        private ConcurrentDictionary requests = new ConcurrentDictionary();
    
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
    
            {
                StringBuilder parameters = new StringBuilder();
    
                _logger.LogError("Error while executing action:" + context.ActionDescriptor.DisplayName);
    
                string errRequest;
                if(requests.TryGetValue(context.HttpContext.TraceIdentifier,out errRequest))
                {
                    _logger.LogError(errRequest);
                }
    
                _logger.LogError(context.Exception);
    
                context.Result = new ObjectResult("Error!!!")
                {
                    StatusCode = 500,
                };
                context.ExceptionHandled = true;
            }
    
            string req;
                requests.Remove(context.HttpContext.TraceIdentifier, out req);
    
    
        }
    
        public void OnActionExecuting(ActionExecutingContext context)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var arg in context.ActionArguments)
            {
    
                sb.Append(arg.Key.ToString() + ":" + Newtonsoft.Json.JsonConvert.SerializeObject(arg.Value) + "\n");
    
            }
            requests.TryAdd(context.HttpContext.TraceIdentifier, sb.ToString());
        }
    
    
    }
    

    }

提交回复
热议问题