响应已被应用程序刷新

时间:2016-03-16 10:00:17

标签: c# asp.net xml vb.net response

ASP .Net app(普通网页)

在页面加载时调用以下方法。为简洁起见,我用一个整数替换了For循环,但实际上这是一个从数据库中获取Customers的循环:

Private Sub GenerateXml
    Dim XDoc As XDocument = <?xml version="1.0"?><Customers></Customers>
    Dim mystring As String = String.Empty

    For i As Integer = 0 To 10
        XDoc.Root.Add(<customer>
                          <id><%= i %></id>
                          <name>Test <%= i %></name>
                      </customer>)
    Next

    Using sw = New MemoryStream()
        Using strw = New StreamWriter(sw, System.Text.UTF8Encoding.UTF8)
            XDoc.Save(strw)
            mystring = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray())
        End Using
    End Using

    Response.Clear()
    Response.Buffer = True
    Response.Charset = ""
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.ContentType = "application/xml"
    Response.Write(mystring)
    Response.Flush()
    Response.End()
End Sub

我开始收到错误“必须在文档根元素之前定义DTD ”。导致添加MemoryStreamStreamWriter以避免此问题。在测试期间,这似乎有效。第二天我收到类似的错误,但指向Chrome中的一行(错误是间歇性的):

  

此页面包含以下错误:       第8行第123行的错误:文档末尾的额外内容       下面是第一个错误的页面呈现。

所以我查看View Source中的页面转到第123行并看到此标记

</Customers><!DOCTYPE html>

(注意错误发生在生成的XML的末尾)。其中添加了DOCTYPE(不知道为什么)????所以搜索了这个错误导致我查看服务器上的错误日志。服务器上列出了以下错误

Log Name:      Application
Source:        ASP.NET 4.0.30319.0
Event ID:      1309
Task Category: Web Event
Level:         Warning
Keywords:      Classic
User:          N/A

Description:
Event code: 3005 
Event message: An unhandled exception has occurred.  
Exception type: HttpException 

Exception message: Session state has created a session id, but cannot save it because the response was already flushed by the application.
   at System.Web.SessionState.SessionIDManager.SaveSessionID(HttpContext context, String id, Boolean& redirected, Boolean& cookieAdded)
   at System.Web.SessionState.SessionStateModule.CreateSessionId()
   at System.Web.SessionState.SessionStateModule.DelayedGetSessionId()
   at System.Web.SessionState.SessionStateModule.ReleaseStateGetSessionID()
   at System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs)
   at System.Web.SessionState.SessionStateModule.OnEndRequest(Object source, EventArgs eventArgs)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

这让我觉得生成的XML很好但是其他东西导致了问题。我唯一能想到的就是删除这行

Response.Flush()

但我不知道这是否能解决问题 - 我知道我可以尝试这个但是考虑到错误是间歇性的我正在寻找一个完整的解决方案以防有人知道我在这里做错了什么?

0 个答案:

没有答案