Search code examples
asp.net-web-apiactionfilterattribute

ASP.NET WebAPI - Pass object from Custom Action Filter to Action


As per this question here, ASP.NET MVC Pass object from Custom Action Filter to Action

, (which is for MVC), is there a similar object that we can add items or values to from within

public override void OnActionExecuting(HttpActionContext actionContext)
{
}

, (which is for WebAPI), and access it seconds later in the Controller's action method itself ?


Solution

  • This works:

    set data:

    public class MyAwesomeFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //add stuff here.. to be accessed later
            actionContext.Request.Properties.Add("myKey69", myValue);
    
        }       
    }   
    

    retrieve data:

    [MyAwesomeFilter]
    public IHttpActionResult MyController( [FromBody] string myParmStr ) {
    
        //retrieve the obj you inserted in filter...
        obj myValue = null;
        if (Request.Properties.TryGetValue("myKey69", out myValue)) {
            //logic here...
        }
    
    }