2016-03-02 53 views
4

我試圖圍繞我的web api調用實現一些日誌記錄。沒什麼特別的,但我仍然在學習異步/等待,並希望在不中斷性能的情況下進行日誌記錄。C#覆蓋OnActionExecutingAsync Web API調用

這是我想要實現的一個例子,只是不完全確定如何去做。

public class Logging : ActionFilterAttribute 
{ 
    public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) 
    { 
     // DoLoggingHere(); ???? 
     base.OnActionExecutingAsync(actionContext, cancellationToken); 
     // OrDoLoggingHere(); ???? 

     // Also, what does the return look like if any? 
    } 

    public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 
    { 
     // This method should/could complete before the logging completes. 
     base.OnActionExecutedAsync(actionExecutedContext, cancellationToken); 

     // Might log here too. 
    } 
} 

基本上我不希望我的任何日誌記錄阻礙HTTP調用。它應該是透明的。

尋找任何幫助!

回答

1

您可以等待調用,因此返回線程彙集更多的傳入請求,然後做記錄通話完成後:

var result = await base.OnActionExecutingAsync(actionContext, cancellationToken); 
// logging code here 

return result; 
+0

能base.OnActionExecutedAsync()來之前,我的記錄結束叫什麼名字? –

+0

您的日誌記錄將在OnActionExecuting返回一些結果之後完成,因爲我們正在等待它,而且它會在OnActionExecuted被調用之前完成 –

+0

我正在尋求相反的結果。我想先看到OnActionExecuted,然後是我的日誌記錄。 –