user68575
user68575

Reputation: 29

Object reference not set to an instance of an object

I am seeing following exception.

System.NullReferenceException: Object reference not set to an instance of an object. 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)

I already have following checks on the context to which I am responding.

return !(context == null || context.Response == null ||
    context.Response.OutputStream == null ||
    !context.Response.OutputStream.CanWrite);

Can anyone hint on what could be causing this?

Upvotes: 1

Views: 2807

Answers (5)

Jonathan Oliver
Jonathan Oliver

Reputation: 5267

I had this error while working with asynchronous handlers and modules. My problem was that I would use ThreadPool.QueueUserWorkItem from within the HttpHandler's EndProcessRequest method and within the work item callback I would try to use the HttpContext. The trouble is once EndProcessRequest returns back to the caller (but the work item callback has not yet been invoked), the HttpContext object instance is no longer "mine" and ASP.NET has assumed control and is tearing it down. See http://odetocode.com/articles/112.aspx for more info.

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82335

This might be happening if you are trying to actually write a null object to the buffer IE:

context.Response.OutputStream.Write(null, 0, 0);

Also You could represent it as...

return (context != null && context.Response != null &&
    context.Response.OutputStream != null &&
    context.Response.OutputStream.CanWrite);

Upvotes: 0

recursive
recursive

Reputation: 86064

I think your error is elsewhere, but I'd suggest writing this expression a little more directly without the negatives:

return context != null && context.Response != null &&
    context.Response.OutputStream != null &&
    context.Response.OutputStream.CanWrite;

Upvotes: 0

Tundey
Tundey

Reputation: 2965

Are you sure that's where the error is? Looks like the exception started from the Write method of HttpResponse.

Upvotes: 1

casperOne
casperOne

Reputation: 74530

Why even bother with all of those checks? Why not just write out to the output stream and be done with it?

Also, where in the ASP.NET processing pipeline is this call being made?

Upvotes: 0

Related Questions