Reputation: 31
I am using IExceptionLogger and ExceptionHandler for logging and error handling globally for my web api service.
Now Is there any way to read the POST data from ExceptionLoggerContext context. ? Just because i would like to save the POST data along with exception details.
Upvotes: 3
Views: 1945
Reputation: 35597
The only way I've found is to parse the ExceptionLoggerContext.ExceptionContext
in your ExceptionLogger
/IExceptionLogger
implementation.
ExceptionLoggerContext.ExceptionContext
is of type System.Web.Http.ExceptionHandling.ExceptionContext
.
There are a few nested objects you have to navigate, but at some point, you will find:
((System.Web.Http.ApiController)exceptionContext.ControllerContext.Controller).ActionContext.ActionArguments
which contains a ValueCollection
with all the arguments of your FORM
.
In my solution I've implemented something like this:
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)
{
}
}
}
I pass my constructor ExceptionLoggerContext.ExceptionContext
; it will populate the dictionary ActionArguments
with all the values posted.
You can find a demo project on Github. It's a self-hosted (owin) web.api application.
In my Startup I've defined my custom implementation of IExceptionLogger
and IExceptionHandler
.
In this sample app I've used Serilog to stream exception on disk.
If you try to post a form to the test controller, I'll throw an exception which will be trapped by a global handler and persisted on the file system with some info.
If you download and run the example found in Github you can use Fiddler to test it:
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
Upvotes: 5