Search code examples
c#asp.netasp.net-web-apiasp.net-core-2.1

How to differentiate between two rest calls in C# in OnActionExecuting of ActionFilterAttribute


I have written my own custom attribute deriving from ActionFilterAttribute say [TestAttr]. I am overriding the method OnActionExecuting and OnResultExecuted. I have also added a check that my [TestAttr] is applied on a controller method like below

public override void OnActionExecuting(ActionExecutingContext context)
{
   if (context.ActionDescriptor is ControllerActionDescriptor)
   {
       //Need to store a variable int x = 100 here which I want to use later on OnResultExecuted method.
       //value of x will keep on changing for different requests. 
       //Is there any way to differentiate between two requests when we land here.
   }
}

public override void OnResultExecuted(ResultExecutedContext context)
{
   if (context.ActionDescriptor is ControllerActionDescriptor)
   {
       //Do Desired stuff.
       //Use the value of x
   }
}

Basically, I want to do the following OnActionExecuting method call ActualRestCall OnResultExecuted method call

But I want to store a value in OnActionExecuting call and later use it in the OnResultExecuted method. And this should not overwrite values in multiple requests.


Solution

  • You could use HttpContext.Items to store values for use later on in the request flow. For example:

    public class FooAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // Store the value...
            context.HttpContext.Items.Add("MyValue", 100);
    
            base.OnActionExecuting(context);
        }
    
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            // Retrieve the value...
            if (context.HttpContext.Items.TryGetValue("MyValue", out var value))
            {
                // We know this is an int so cast it
                var intValue = (int)value;
            }
    
            base.OnResultExecuted(context);
        }
    }