Web API操作过滤器修改返回值

24
我有一个Web API应用程序,需要通过ActionFilter的OnActionExecuted方法获取一些API端点的返回值。我使用自定义属性来识别需要修改数据的端点,但是我无法在HttpActionExecutedContext中找到实际的结果对象。谢谢任何帮助!
1个回答

46

您可以通过 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
        }
    }
}

谢谢您的回复。context.Response.Content 的类型是 System.Net.Http.ObjectContent<System.Collections.Generic.IEnumerable<Model.ViewModels.UserAction>>。我只需要 System.Collections.Generic.IEnumerable<Model.ViewModels.UserAction> 部分。我该如何获取它? - joe_coolish
ObjectContent<T>是从ObjectContent派生的,所以只需将context.Response.Content强制转换为ObjectContent,然后就可以使用Value属性将其转换为您的IEnumerable<Model.ViewModels.UserAction>... - nemesv
这对我来说完成了任务。谢谢。 - Stanley Okpala Nwosa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接