我已經創建了一個ActionFilter來試圖控制我們的API客戶端的數據使用情況,以便我們可以查明行爲異常的客戶端。動作過濾器是微不足道的:計算HttpRequestMessage和HttpResponseMessage總長度
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CollectDeviceDataUsageAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
if (actionExecutedContext.ActionContext.ActionArguments.ContainsKey("id")) {
long id = (long)actionExecutedContext.ActionContext.ActionArguments["id"];
var action = actionExecutedContext.ActionContext.ActionDescriptor.ActionName.ToUpper();
var method = actionExecutedContext.Request.Method.Method;
var resource = method + " " + action;
IntegraRepository.CollectDeviceUsage(id.ToString(), resource, actionExecutedContext.Request, actionExecutedContext.Response);
}
base.OnActionExecuted(actionExecutedContext);
}
}
它委託數據使用calulcation到CollectDeviceUsage方法。問題是:我不知道如何獲得請求和響應的實際「字節」大小!我可以得到每個的內容長度,但是這不會考慮標題。這並不需要超級精確的數據使用度量,我對TCP/IP開銷不感興趣,但是我認爲HTTP頭開銷是足夠的。
下面是我用得到教改嘗試,lengh代碼:
var sizeReq = request.Content.Headers.ContentLength ?? 0;
var sizeResp = response == null ? 0 : response.Content.Headers.ContentLength ?? 0;
我怎麼可能還收集實際收到的頁眉/發送lenght?像request.Content.Headers.Length東西:-)
UPDATE
這是非常簡單的獲得請求的標頭的長度:
request.Headers.ToString().Length;
麻煩現在只能用頭輸入反應謊言。我相信我沒有足夠的信息在OnActionExecuted方法中找出將發送給客戶端的標題,因爲response.Headers返回一個空集合!
這是它作爲執行HEAD的副產品http://www.strathweb.com/2013/03/adding-http-head-support-to-asp-net-web-api/ – MatthewMartin 2014-09-26 17:22:13
@MatthewMartin我已經嘗試迭代request.Headers集合中ToString方法返回一個字符串並連接請求標頭的所有項後,找出它。所以我現在使用它的長度作爲標題長度(我更新了問題)。現在的問題在於響應,因爲似乎我沒有足夠的信息來知道當我的過濾器運行時,Web.API將在響應客戶端時發送哪些標頭... – Loudenvier 2014-09-26 17:27:11