我正在编写一些代码,其中需要使用自己的 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: 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() 失败,因为您不在 ASP.Net 环境中,而是在控制台/其他非 asp.net 应用程序中。我的猜测是(并通过作弊和使用 Reflector 证实了这一点)Response.End 引用了 HttpContext.Current (或等效的本地副本),该副本为空,因此它会抛出该错误。
调用 Response.End 是其他代码的一种意思。我知道你无法更改它,但如果真的那么担心的话,它可能应该调用 Response.Flush。
关于.net - 为什么我的自定义 HttpResponse 在 HttpResponse.End() 上抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3347991/