Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing Action Parameters from ExceptionLogger

I'm wanting to make use of the new method for globally logging errors. I've written a class that inherits ExceptionLogger and overrides the Log() method. Then registered it as a replacement.

public class TraceExceptionLogger : ExceptionLogger
{
    public async override void Log(ExceptionLoggerContext context)
    {
        //  This is always empty string
        var content = await context.Request.Content.ReadAsStringAsync();

        //  This is almost always null
        var actionContext = context.ExceptionContext.ActionContext;
    }
}

I can dig through the ExceptionLoggerContext object's properties to get pretty much everything I need, EXCEPT for action parameters. There is indeed an ActionContext property but I've only seen it null and this wiki page states that ActionContext and ControllerContext will almost always be null.

Also, I can't get the content stream because its stream is already read before it gets to my logger. So there's no way for me to get any posted json from the request's content.

Is there maybe a way to get the posted data from HttpContext.Current or in some other way?

like image 763
Jeff LaFay Avatar asked Apr 09 '14 18:04

Jeff LaFay


2 Answers

Ok it looks like I can get the body text from HttpContext by reading InputStream on the Request object like this:

string bodyText = string.Empty;

using (var sr = new StreamReader(HttpContext.Current.Request.InputStream))
{
    sr.BaseStream.Seek(0, SeekOrigin.Begin);
    bodyText = sr.ReadToEnd();
}

This code has been successful me so far for getting my posted json data.

like image 188
Jeff LaFay Avatar answered Oct 07 '22 01:10

Jeff LaFay


Here's action parameters for future reference

public class HomeController : ApiController {
    public string Get(string id, [FromHeader] Whoever whoever) {

    public string Post(Whatever whatever) {


var args = ((ApiController) context.ExceptionContext
           .ControllerContext.Controller)).ActionContext.ActionArguments

if (args.ContainsKey("whatever")) {
   var whatever = (Whatever)args["whatever"];
like image 33
Whoever Avatar answered Oct 07 '22 00:10

Whoever