如何从HttpActionExecutedContext获取当前的HttpContext

时间:2015-02-06 16:32:48

标签: asp.net asp.net-web-api httpcontext

我正在写一个异常过滤器来记录Elmah的异常,所以我做了这样的事情:

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的方法,但我找不到任何方法可以到达那里

我如何在这里实现目标?

2 个答案:

答案 0 :(得分:4)

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;

我将这个与monad实现一起使用,允许我使用ErrorSignal.FromCurrentContext()作为后备,到目前为止它运作良好。

答案 1 :(得分:0)

请注意,这可能仅在Web API托管在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);
    }
}