2015-02-06 468 views
2

我正在寫一個異常過濾器將記錄例外ELMAH,所以我在做這樣的事情:如何獲取當前的HttpContext從HttpActionExecutedContext

class ExceptionLoggingFilter : System.Web.Http.Filters.IExceptionFilter 
{ 
    public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actExecContext, 
              CancellationToken cancellationToken) 
    { 
     var httpContext = // what do I do here? 
     var errorSignal = ErrorSignal.FromContext(httpContext); // this is Elmah 
     errorSignal.Raise(actExecContext.Exception, httpContext); 
    } 
} 

我的問題是,我不我不知道該如何置換評論問題。我試圖探索HttpActionExecutedContext,我從方法簽名去找到一種方法,一個System.Web.HttpContext的成員樹,但我找不到任何辦法去那裏。

如何實現我的目標嗎?

+0

'ApiController'不使用'HttpContext'或'HttpContextBase'。你可以使用'HttpContext.Current'來獲取它們,但只有當webapi託管在IIS中。如果您在IIS中託管,我相信您可以執行'ErrorSignal.FromCurrentContext()',或遵循Joanvo的答案。 – danludwig 2015-02-06 17:00:27

+0

@danludwig:我正在IIS中運行此託管,因此可能會起作用。 – 2015-02-06 22:56:54

回答

2
Elmah.ErrorSignal.FromCurrentContext() 

使用HttpContext.Current引擎蓋下,所以雖然該威力有工作,我做了找到一個更好的(雖然更迂迴的)的方式來得到它:

var request = actionExecutedContext.Request; 
object value; 
if (request == null 
    || !request.Properties.TryGetValue("MS_HttpContext", out value) 
    || !(value is HttpContextBase)) 
    return null; // Actually I'm returning a Maybe monad here but that's off topic... 
} 
var httpContextBase = value as HttpContextBase; 
return httpContextBase.ApplicationInstance.Context; 

我一起使用這個有可能實現單子勒我使用ErrorSignal.FromCurrentContext()作爲後備,到目前爲止它運行良好。

0

注時的WebAPI在IIS託管這將可能只工作(不是自我託管):

class ExceptionLoggingFilter : System.Web.Http.Filters.IExceptionFilter 
{ 
    public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actExecContext, 
              CancellationToken cancellationToken) 
    { 
     //var httpContext = // what do I do here? NOTHING 
     var errorSignal = ErrorSignal.FromCurrentContext(); // this is Elmah 
     errorSignal.Raise(actExecContext.Exception); 
    } 
} 
+0

我在IIS中託管,所以這可能會工作。我可以確認我星期一何時回去工作=) – 2015-02-06 22:57:14