【发布时间】:2012-10-06 14:31:37
【问题描述】:
我有一个 Web API 应用程序,我需要通过 ActionFilter 的 OnActionExecuted 方法获取一些 API 端点的返回值
我正在使用自定义属性来识别具有我需要修改的数据的端点,但我似乎无法从 HttpActionExecutedContext 中找到实际的结果对象。
感谢您的帮助!
【问题讨论】:
标签: c# asp.net-web-api action-filter
我有一个 Web API 应用程序,我需要通过 ActionFilter 的 OnActionExecuted 方法获取一些 API 端点的返回值
我正在使用自定义属性来识别具有我需要修改的数据的端点,但我似乎无法从 HttpActionExecutedContext 中找到实际的结果对象。
感谢您的帮助!
【问题讨论】:
标签: c# asp.net-web-api action-filter
可以通过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> 部分。我怎么得到它?
ObjectContent<T> 是从ObjectContent 派生的,所以只需将context.Response.Content 转换为ObjectContent 然后您可以使用Value 属性转换为您的IEnumerable<Model.ViewModels.UserAction>...