Elmah: How to get JSON HTTP request body from error report

岁酱吖の 提交于 2019-11-27 09:25:42

ELMAH so far only logs the context or information that is peripheral to the request and which can be conveniently captured in a standard way. Forms are arguably a special treatment because ASP.NET already does the job of decoding and memorizing request entities when the MIME type is application/x-www-form-urlencoded. JSON requests on the other hand are prolematic because at the time an exception occurs, the input stream (HttpRequest.InputStream) may have been partially or completely consumed by a JSON decoder. ELMAH would not be able to get a second crack at it for the purpose of logging. You will therefore have to make sure that you buffer the input stream or text before passing it through any JSON decoder and stash it away somewhere like HttpContext.Items. You could then try to recover the buffered data and attach it to an outgoing mail at the time of an error. ELMAH currently does not support attaching arbitrary data to a logged error. There is however the ErrorLogModule that has a Logged event and which supplies the Id of the logged error. This could be used to store the input data elsewhere (perhaps in another table if you are using a back-end database for the error logs) but tie it back to the logged error by maintaining an association via the Id.

first install nuget package : Newtonsoft.Json

install-package Newtonsoft.Json

then:

 public override void OnException(HttpActionExecutedContext filterContext)
        {
    var message = new StringBuilder();
            foreach (var param in filterContext.ActionContext.ActionArguments)
            {
                message.Append(string.Format("{0}:{1}\r\n", param.Key, Newtonsoft.Json.JsonConvert.SerializeObject(param.Value)));
            }
            var ex = new Exception(message.ToString(), filterContext.Exception);
            var context = HttpContext.Current;
            ErrorLog.GetDefault(context).Log(new Error(ex, context));
}
Oli Gray

Further to Atif's answer here, there is a way to add additional details to ELMAH log by manually throwing a new Exception. It's not particularly elegant but it seems to do the job!

I'd be interested to hear any comments from the man himself...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!