[英]How do I get the current HttpContext from a HttpActionExecutedContext
I'm writing an exception filter that will log exceptions to Elmah, so I'm doing something like this: 我正在编写一个异常过滤器,该异常过滤器会将异常记录到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);
}
}
My problem is that I don't know what to put in place of the comment question. 我的问题是我不知道该用什么代替评论问题。 I've tried to explore the member tree of the
HttpActionExecutedContext
that I get from the method signature to find a way to a System.Web.HttpContext
, but I can't find any way to get there. 我试图探索从方法签名获得的
HttpActionExecutedContext
的成员树,以找到通向System.Web.HttpContext
,但是我找不到任何方法可以到达那里。
How do I accomplish my goal here? 我如何在这里实现目标?
Elmah.ErrorSignal.FromCurrentContext()
uses HttpContext.Current
under the hood, so although that might have worked I did find a better (albeit more roundabout) way to get to it: 在
HttpContext.Current
使用HttpContext.Current
,因此尽管这可能 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;
I'm using this together with a maybe monad implementation that lets me use ErrorSignal.FromCurrentContext()
as fallback, and so far it's worked well. 我将其与可能是monad的实现结合使用,使我可以将
ErrorSignal.FromCurrentContext()
用作后备,到目前为止,它运行良好。
Note this will probably only work when the WebAPI is hosted in IIS (not self-hosted): 请注意,这可能仅在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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.