2016-03-15 17 views
2

我有相当多的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?

谢谢。

+1

你有没有考虑过把它写到你的过滤器的Http Response Header中? – Igor

回答

4

您可以像这样将它添加到Http Response标头。那么你不会破坏任何现有的代码,感兴趣的客户可以检索它。

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) 
{ 
    base.OnActionExecuted(actionExecutedContext); 

    Stopwatch stopwatch = (Stopwatch)actionExecutedContext.Request.Properties[StopwatchKey]; 

    long delay = stopwatch.ElapsedMilliseconds; 
    actionExecutedContext.Response.Headers.Add("requestTime", delay.ToString()); 
} 

您也可以在WebApiConfig.cs文件中全局注册过滤器。

+0

简单而不破坏。尼斯。 – granadaCoder

+0

非常感谢,这正是我所追求的!是的,过滤器是全局注册的,我只是想在示例代码中演示它正在被应用。 – user176504