Web API ActionFilter修改返回的值

joe*_*ish 22 c# action-filter asp.net-web-api

我有一个Web API应用程序,我需要通过ActionFilter的OnActionExecuted方法获得一些API端点的返回值

我正在使用自定义属性来标识具有我需要修改的数据的端点,但我似乎无法从HttpActionExecutedContext中找到实际的结果对象.

谢谢你的帮助!

nem*_*esv 43

您可以通过该Response.Content属性获取返回的值.如果您的操作已返回对象,则可以将其强制转换ObjectContent为可以获取返回值的实际实例的位置:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)