我有相当多的Web API应用程序,几个不同的系统用于收集数据。我被要求为每个方法的执行结果添加一个属性。我可以在动作过滤器中使用OnActionExecuting/OnActionExecuted来完成此操作,但是我需要制定出返回时间的最佳方式,而不会破坏我已有的内容。将属性添加到Web API输出的最佳实践
对于更复杂的对象,我可以有类地从包含TimeTaken财产基类扩展:
public class ApiBaseModel {
public int TimeTaken {get;set;}
}
public class ApiModel : ApiBaseModel {
// other properties
}
// in Web API controller
[ApiTimeTakenFilter]
[HttpGet]
public ApiModel GetApiModel() {
return new ApiModel();
}
// in filter
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
actionContext.Request.Properties[StopwatchKey] = Stopwatch.StartNew();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
Stopwatch stopwatch = (Stopwatch)actionExecutedContext.Request.Properties[StopwatchKey];
long delay = stopwatch.ElapsedMilliseconds;
var objectContent = actionExecutedContext.Response.Content as ObjectContent;
if (objectContent != null)
{
var value = objectContent.Value; //holding the returned value
if (value is ApiBaseModel)
{
// put the delay into the object
((ApiBaseModel)value).TimeTaken = delay;
}
}
}
这应该是在不打破了以前版本的API很好,但我有很多的返回简单对象的方法,如
[ApiTimeTakenFilter]
[HttpGet]
public bool IsOK {
return true;
}
所以,如果我改变了一个复杂的返回类型,我会打破现有用户的API的完整性。
是否有一些其他机制可以用于传递所有方法的TimeTaken值,而不会破坏API?
谢谢。
你有没有考虑过把它写到你的过滤器的Http Response Header中? – Igor