WebMethod in ASP.NET global error handler: how to

2020-03-30 15:52发布

问题:

Stated another way, using HttpContext, how can I retrieve the parameters passed to a [WebMethod] when in a global error handler?

Kovu gives a great example of how to do a global error trap to grab [WebMethod] errors in Global.asax, which I think he got from Richard Liu here, but his solution does not capture the parameters passed to the WebMethod, and I really need to log these to repro the errors.

I adapted Richard/Kovu's example to start trapping more things about the request, but I just can't find where the input parameters for the [WebMethod] are hidden.

/*  global.asax */
protected void Application_PostMapRequestHandler(object sender, EventArgs e)
{
    /*    REQUIRES         
      <system.web>
        <customErrors mode="Off"/>
        TO WORK IN PRODUCTION
    */

    HttpContext context = HttpContext.Current;
    if (context.Handler is Page && !string.IsNullOrEmpty(context.Request.PathInfo))
    {
        string contentType = context.Request.ContentType.Split(';')[0];
        if (contentType.Equals("application/json", StringComparison.OrdinalIgnoreCase))
        {
            context.Response.Filter = new PageMethodExceptionLogger(context);
        }
    }
}

using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;

public class PageMethodExceptionLogger : Stream
{
    private readonly HttpContext _context;
    private readonly Stream _baseStream;
    private readonly MemoryStream _capturedStream = new MemoryStream();

    public PageMethodExceptionLogger(HttpContext context)
    {
        _context = context;
        _baseStream = context.Response.Filter;
    }

    public override void Close()
    {
        if (_context.Response.StatusCode == 500 && _context.Response.Headers["jsonerror"] == "true")
        {

            string sErr = "trapped json error, probably in [WebMethod]:\r\n\r\n";

            //this will log the error and stack trace.
            _capturedStream.Position = 0;
            string responseJson = new StreamReader(_capturedStream).ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            var jsonObject = js.DeserializeObject(responseJson) as Dictionary<string, object>;
            foreach (string sKey in jsonObject.Keys)
                sErr += string.Format("{0}:\r\n{1}\r\n\r\n", sKey, jsonObject[sKey]);

            //============= LOG THE INPUT PARAMETERS ========================================================

            sErr += "\r\n=== Request ===\r\n";
            sErr += "Content Type = " + _context.Request.ContentType + "\r\n";
            sErr += "Content Encoding = " + _context.Request.ContentEncoding.BodyName + "\r\n";
            _context.Request.InputStream.Position = 0;


        //========= this holds the parameters passed to the [WebMethod] ========
        // It holds a JSON string, so could deserialize as above, but 
        //   useful to see the original string format for debugging 
        //   purposes, as the json format could be the issue that triggered this log!! ;-)
        sErr += "\r\n=== INPUT ===\r\n";
        try
        {
            long iReadLen = _context.Request.InputStream.Length;
            if (iReadLen > 0)
            {
                var bytes = new byte[iReadLen];
                _context.Request.InputStream.Position = 0;
                _context.Request.InputStream.Read(bytes, 0, (int)iReadLen);
                sErr += System.Text.Encoding.UTF8.GetString(bytes) + "\r\n";
            }
            else
            {
                sErr += "Request.InputStream is empty\r\n";
                sErr += System.Text.Encoding.Default.GetString(_context.Request.BinaryRead(_context.Request.TotalBytes));

            }
        }
        catch(Exception oEx)
        {
            sErr += "Error reading Request.InputStream; " + oEx.Message;
        }

            sErr += "\r\n=== HEADERS ===\r\n";
            sErr += HttpUtility.UrlDecode(_context.Request.Headers.ToString()).Replace("&", "\r\n") + "\r\n";

            sErr += "\r\n=== USER ===\r\n";
            try
            {
                sErr += "Current User = " + _context.User.Identity.Name + "\r\n\r\n";
            }
            catch
            {
                sErr += "oContext.User.Identity.Name could not be retrieved!!!\r\n\r\n";
            }


            //====== LOG THE SESSION ========
            sErr += "\r\n=== Session Variables ===\r\n";
            if (_context.Session == null)
            {
                sErr += "session object is null\r\n";
            }
            else
            {
                sErr += "There are " + _context.Session.Count.ToString() + " session variables\r\n";
                foreach (string sKey in _context.Session)
                {
                    sErr += sKey + "=" + _context.Session[sKey].ToString() + "\r\n";
                }
            }

            sErr += "\r\n";

            clsErrorHandler.LogMessage(sErr);

        }

        _baseStream.Close();
        base.Close();
    }

    public override void Flush()
    {
        _baseStream.Flush();
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return _baseStream.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
        _baseStream.SetLength(value);
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        return _baseStream.Read(buffer, offset, count);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        _baseStream.Write(buffer, offset, count);
        _capturedStream.Write(buffer, offset, count);
    }

    public override bool CanRead { get { return _baseStream.CanRead; } }
    public override bool CanSeek { get { return _baseStream.CanSeek; } }
    public override bool CanWrite { get { return _baseStream.CanWrite; } }
    public override long Length { get { return _baseStream.Length; } }

    public override long Position
    {
        get { return _baseStream.Position; }
        set { _baseStream.Position = value; }
    }
}

Now this code gives the following output. (the formatting is messed up because I can't figure out how to use the SO WYSIWYG editor, sorry).

============================================================ trapped json error, probably in [WebMethod]:

Message: Invalid object passed in, ':' or '}' expected. (23): {'sKitName':'christin'a'}

StackTrace: at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)

ExceptionType: System.ArgumentException

=== INPUT === {'sKitName':'christin'a'}

=== HEADERS === Connection=keep-alive Content-Length=25 Content-Type=application/json; charset=UTF-8 Accept=application/json, text/javascript, /; q=0.01 Accept-Encoding=gzip, deflate Accept-Language=en-US,en;q=0.9 Cookie=.ADAuthCookie=A12630A2F7FEA673C36FDC28C7625ED4C4C92760B0EEE6C68C8068FF81A8773DF1916B4A067326576F4D067D4C26C874A9C3C96D81F74D15E0452EDD743C3472F530DE5E6542E8DE1DD19BF76114702F70AF483DBF963C8686727CB541151EBF32322CD647ADD6D9FC01C4785393227F19341D2BE320DF821E0E223A24B7FBB5E5CA7F79D87815AF49AF24C455CA81FD; ASP.NET_SessionId=iqc0ztobmcva4lqbtii222fa Host=web04.local Referer=http://web04.local/APP/Chem_View/Reagent_Kit_Inventory.aspx User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 Origin=http://web04.local X-Requested-With=XMLHttpRequest

=== USER === Current User = lila.whitehead

=== Session Variables === There are 1 session variables dtTouched=

At 9/9/2019 2:37:00 PM

============================================================