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