2012-10-06 50 views
20

我有我需要通過一個ActionFilter的OnActionExecuted方法得到阿霍德的一些API端點的返回值的一個Web API應用程序的Web API ActionFilter修改返回值

我使用的是自定義屬性標識具有需要修改的數據的端點,但我似乎無法從HttpActionExecutedContext中找到實際的結果對象。

感謝您的幫助!

回答

37

您可以通過Response.Content屬性獲取返回的值。

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 
     } 
    } 
} 
+0

感謝您的答覆:如果你的動作返回一個對象,你可以從那裏你可以得到的返回值的實際情況將其轉換爲ObjectContent。 'context.Response.Content'的類型是'System.Net.Http.ObjectContent >'。我只想要'System.Collections.Generic.IEnumerable '部分。我如何獲得? –

+0

'ObjectContent '是派生形式'ObjectContent',所以只需將'context.Response.Content'投入'ObjectContent',然後你就可以使用'Value'屬性投射到你的'IEnumerable '.. 。 – nemesv