我使用IExceptionLogger和ExceptionHandler爲我的web api服務進行全局記錄和錯誤處理。Web API ExceptionLogger
現在有什麼方法可以從ExceptionLoggerContext上下文中讀取POST數據。 ?僅僅因爲我想保存POST數據以及異常詳細信息。
我使用IExceptionLogger和ExceptionHandler爲我的web api服務進行全局記錄和錯誤處理。Web API ExceptionLogger
現在有什麼方法可以從ExceptionLoggerContext上下文中讀取POST數據。 ?僅僅因爲我想保存POST數據以及異常詳細信息。
我發現的唯一方法是在您的ExceptionLogger
/IExceptionLogger
實施中解析ExceptionLoggerContext.ExceptionContext
。
ExceptionLoggerContext.ExceptionContext
的類型是System.Web.Http.ExceptionHandling.ExceptionContext
。
有你導航幾個嵌套的對象,但在某些時候,你會發現:
((System.Web.Http.ApiController)exceptionContext.ControllerContext.Controller).ActionContext.ActionArguments
其中包含與FORM
的所有參數的ValueCollection
。
在我的解決方案,我實現了這樣的事情:
public class MyExceptionContext
{
public Dictionary<string, object>.ValueCollection ActionArguments { get; set; }
public MyExceptionContext(System.Web.Http.ExceptionHandling.ExceptionContext exceptionContext)
{
try
{
this.ActionArguments = ((System.Web.Http.ApiController)exceptionContext.ControllerContext.Controller).ActionContext.ActionArguments.Values;
}
catch (Exception)
{
}
}
}
我通過我的構造ExceptionLoggerContext.ExceptionContext
;它將填充發布的所有值的字典ActionArguments
。
你可以在Github上找到demo project。這是一個自主託管的(owin)web.api應用程序。 在我的Startup中,我定義了我的自定義實現IExceptionLogger
和IExceptionHandler
。
在這個示例應用程序中,我用Serilog在磁盤上傳送異常。
如果您嘗試將表單發佈到測試控制器,我將throw an exception這將被全局處理程序捕獲並在文件系統上保留一些信息。
如果您下載並運行在Github上找到的例子,你可以使用Fiddler來測試它:
POST http://localhost:9667/api/exception HTTP/1.1
User-Agent: Fiddler
Content-Type: application/x-www-form-urlencoded
Host: localhost:9667
Content-Length: 40
username=stackoverflow&password=password