【发布时间】:2014-05-16 19:48:42
【问题描述】:
我们正在为我们的 WebAPI 实现一个全局异常处理程序(如在此链接中)
http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling
我们还使用 log4net 的 LogicalThreadContext 来传递上下文信息(如调用上下文 id 或相关 id)。对于那些不熟悉的人,这使用 CallContext.LogicalSetData 和 LogicalGetData。
我的问题是,一旦我进入我们的自定义 ExceptionLogger 和 ExceptionHandler 类,我似乎无法访问数据。下面是我的意思的一个非常精简/伪代码。
为什么会发生这种情况的想法?
public MyResponse Get(string someId)
{
CallContext.LogicalSetData("mytest", "555");
LogicalThreadContext.Properties["anotherprop"] = "999";
string contextValue = CallContext.LogicalGetData("mytest") as string;
string contextValue2 = LogicalThreadContext.Properties["anotherprop"] as string;
throw new Exception("Fake exception that I am logging");
}
public class HttpExceptionLogger : ExceptionLogger
{
public override void LogCore(ExceptionLoggerContext context)
{
// PROBLEM: this is null
string contextValue = CallContext.LogicalGetData("mytest") as string;
// this is okay, returns '999'
string contextValue2 = LogicalThreadContext.Properties["anotherprop"] as string;
// do some logging, etc.
}
public class HttpExceptionHandler : ExceptionHandler
{
public override void HandleCore(ExceptionHandlerContext context)
{
// PROBLEM: this is null
string contextValue = CallContext.LogicalGetData("mytest") as string;
// PROBLEM: this is also null
string contextValue2 = LogicalThreadContext.Properties["anotherprop"] as string;
// return a message to the user, e.g.
string message = string.Format("unexpected exception, ref Id={0}, ref Id2={1}", contextValue, contextValue2);
context.Result = new TextPlainExceptionResult
{
Request = context.ExceptionContext.Request,
Content = message
};
}
【问题讨论】:
标签: .net asp.net-web-api exception-handling