我們正在實現我們的WebAPI一個全球性的異常處理程序(如在此鏈接)問題什麼時候CallContext LogicalSetData被清除?用的WebAPI全球的ExceptionHandler
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類。下面是我的意思是一個非常簡潔/ pseduo代碼。
想法爲什麼發生這種情況?
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
};
}