Web API ActionFilter modify returned value

2020-07-01 16:43发布

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!

1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-01 17:26

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
        }
    }
}
查看更多
登录 后发表回答