C# – Web API ActionFilter modify returned value

action-filterasp.net-web-apic

I have a Web API application that I need to get ahold of the return value of some of the API endpoints via an ActionFilter's OnActionExecuted method

I'm using a custom attribute to identify the endpoints that have data that I need to modify, but I can't seem to find the actual result object from within the HttpActionExecutedContext.

Thanks for any help!

Best Answer

You can get the returned value through the Response.Content property. If your action has returned an object you can cast it to ObjectContent from where you can get the actual instance of the returned value:

public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        var objectContent = context.Response.Content as ObjectContent;
        if (objectContent != null)
        {
            var type = objectContent.ObjectType; //type of the returned object
            var value = objectContent.Value; //holding the returned value
        }
    }
}