开发者

System.Diagnostics.Trace.TraceListener UnsafeStringCopy exception from ASP.NET

开发者 https://www.devze.com 2023-01-10 22:04 出处:网络
I get an odd intermittent error when trying to write a Diagnostics.Trace message from an assembly used by an ASP.NET application.It\'s .NET 3.5 on IIS7.

I get an odd intermittent error when trying to write a Diagnostics.Trace message from an assembly used by an ASP.NET application. It's .NET 3.5 on IIS7.

The code setup is that when web.config has debug specified I add an instance of HttpResponseTraceListener to System.Diagnostics.Trace.Listeners. I'm doing it that way so in my other assembly I can write out debug information when running on a test server that I'm not set up to debug using visual studio. So in my other assembly I use System.Diagnostics.Trace.WriteLine to output information, which then also gets written to the response stream (inline, but for my purpose that is just fine).

The error is:

Object reference not set to an instance of an object.

The relevant stack 开发者_StackOverflowinformation is:

at System.Web.Util.StringUtil.memcpyimpl(Byte* src, Byte* dest, Int32 len) at System.Web.Util.StringUtil.UnsafeStringCopy(String src, Int32 srcIndex, Char[] dest, Int32 destIndex, Int32 len) at System.Web.HttpWriter.Write(String s) at System.Web.HttpResponse.Write(String s) at SSO.HttpResponseTraceListener.Write(String message) in HttpResponseTraceListener.cs:line 23 at SSO.HttpResponseTraceListener.WriteLine(String message) in HttpResponseTraceListener.cs:line 30 at System.Diagnostics.TraceInternal.WriteLine(String message)

The TraceListener class is as follows:

public class HttpResponseTraceListener : TraceListener
{
    public System.Web.HttpResponse Response { get; private set; }
    public HttpResponseTraceListener(System.Web.HttpResponse response)
    {
        Response = response;
    }
    public override void Write(string message)
    {
        if (!string.IsNullOrEmpty(message)
         && null != Response
         && null != Response.OutputStream
         && Response.OutputStream.CanWrite)
        {
            Response.Write(System.Web.HttpUtility.HtmlEncode(message));
        }

    }

    public override void WriteLine(string message)
    {
        this.Write(message);
        Response.Write("<BR />");
    }
}


Looks like the problem was that the TraceListeners never were detached. So each time I hit the page I added another one. And each time I wrote to Diagnostics.Trace it would write to all that were attached. But for some the Response object was not able to be written to.

To fix it I added code to not write if there was an exception. And also added code to remove the listener when the page was done loading.

0

精彩评论

暂无评论...
验证码 换一张
取 消