我正在编写一些代码,我需要使用自己的HttpResponse
对象来捕获另一个以HttpResponse
为参数的对象的方法输出。问题是,这个其他对象(我无法修改)调用HttpResponse.End()
,这会导致“对象引用未设置为对象的实例”异常被抛出。我该怎么办?
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
以下是有关错误的更完整信息,从控制台应用程序中的以下代码中抛出:
Dim myStringbuilder As New StringBuilder
Dim myStringWriter As New IO.StringWriter(myStringbuilder)
Dim myResponse As New Web.HttpResponse(myStringWriter)
Try
myResponse.End()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
以下是例外文本:
System.NullReferenceException:未将对象引用设置为对象的实例。 在System.Web.HttpResponse.End() 在C:\ Documents and Settings \ joe.user \ Local Settings \ Application Data \ Temporary Projects \ ConsoleApplication1 \ Module1.vb:第10行中的ConsoleApplication1.Module1.Main()中
答案 0 :(得分:2)
Response.End()失败,因为你不在ASP.Net环境中,你在控制台/其他nonasp.net应用程序中。我的猜测是(并通过欺骗和使用Reflector确认)Response.End引用了HttpContext.Current(或equivelant local copy),它是null,因此它会抛出该错误。
调用Response.End是其他代码的意思。我知道你不能改变它,但如果真的那么担心,它可能应该调用Response.Flush。
答案 1 :(得分:1)
如果您在Visual Studio中运行代码,请尝试在不启用调试器的情况下执行代码(Ctrl F5):不应该引发异常。它对我有用。