I'm writing some code in which I need to use my own HttpResponse
object to capture the output from a method on another object that takes an HttpResponse
as a parameter. The problem is, this other object (which I cannot modify) calls HttpResponse.End()
, which causes an "Object reference not set to an instance of an object" exception to be thrown. What can I do about this?
Dim myStringbuilder As New StringBuilder
Dim myStringWriter As New IO.StringWriter(myStringbuilder)
Dim myResponse As New Web.HttpResponse(myStringWriter)
someObject.doStuffWithHttpResponse(myResponse) ' calls myResponse.End() and crashes
Here's some more complete information about the error, thrown from the following code in a console application:
Dim myStringbuilder As New StringBuilder
Dim myStringWriter As New IO.StringWriter(myStringbuilder)
Dim myRespons开发者_开发知识库e As New Web.HttpResponse(myStringWriter)
Try
myResponse.End()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
Here's the text of the exception:
System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.HttpResponse.End() at ConsoleApplication1.Module1.Main() in C:\Documents and Settings\joe.user\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Module1.vb:line 10
Response.End() is failing because your not in an ASP.Net environment, your in a console/other non-asp.net application. My guess was (and confirmed it by cheating and using Reflector) that Response.End references HttpContext.Current (or equivelant local copy), which is null, so it throws that error.
calling Response.End is kind of mean of that other code. I know you can't change it but it should probably be calling Response.Flush if it's really that worried.
If you're running your code in Visual Studio, try to execute your code without the debugger on (Ctrl F5): The exception should not be raised then. It worked for me.
精彩评论