我有一个Web API应用程序,需要通过ActionFilter的OnActionExecuted方法获取一些API端点的返回值。我使用自定义属性来识别需要修改数据的端点,但是我无法在HttpActionExecutedContext中找到实际的结果对象。谢谢任何帮助!
您可以通过 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_coolishObjectContent<T>
是从ObjectContent
派生的,所以只需将context.Response.Content
强制转换为ObjectContent
,然后就可以使用Value
属性将其转换为您的IEnumerable<Model.ViewModels.UserAction>
... - nemesv