鉴于 Steven 的警告,答案可能是在 Page_Load 事件中首先使用 Tom Holland's test 手动解析 Request.InputStream,然后是 XDocument.Load。
在我问这个问题之前启动了谷歌搜索,但后来才检查,发现this,也表明我在正确的轨道上。
我还想问我的观点所暗示的问题,即响应也必须是 XML,什么是最好的方法,但我找到了答案 here。
综上,最终代码为:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Request.ContentType <> "text/xml" Then _
Throw New HttpException(500, "Unexpected Content-Type")
Dim id = CheckBasicAuthentication
Dim textReader = New IO.StreamReader(Request.InputStream)
CheckXmlValidity(textReader)
' Reset the stream & reader
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim xmlIn = XDocument.Load(textReader)
' process XML in xmlIn
Dim xmlOut = <?xml version="1.0" encoding="UTF-8" ?>
<someresult>
<header>
<id><%= id.ToString() %></id>
<datestamp>To be inserted</datestamp>
</header>
<result/>
</someresult>
' Further generation of XML for output
xmlOut.<someresult>.<header>.<datestamp>.Value = Date.UtcNow.ToString(xmlDateFormat)
xmlText.Text = xmlOut.ToString
End Sub
Private Function CheckBasicAuthentication() As Integer
Dim httpAuthorisation = Request.Headers("Authorization")
If Left(httpAuthorisation, 6).ToUpperInvariant <> "BASIC " Then _
Throw New HttpException(401, "Basic Authentication Required")
Dim authorization = Convert.FromBase64String(Mid(httpAuthorisation, 7))
Dim credentials = Text.Encoding.UTF8.GetString(authorization).Split(":"c)
Dim username = credentials(0)
Dim password = credentials(1)
Return ConfirmValidUser(username, password)
End Function
Private Shared Sub CheckXmlValidity(ByVal textReader As System.IO.StreamReader)
Try
' Check for "interesting" xml documents.
Dim settings = New System.Xml.XmlReaderSettings()
settings.XmlResolver = Nothing
settings.MaxCharactersInDocument = 655360
' Successfully parse the file, otherwise an XmlException is to be thrown. '
Dim reader = System.Xml.XmlReader.Create(textReader, settings)
Try
While reader.Read()
'Just checking.
End While
Finally
reader.Close()
End Try
Catch ex As Exception
Throw New HttpException(500, "Invalid Xml data", ex)
End Try
End Sub
而 ASP.NET 网页.aspx 是:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="webpage.aspx.vb" Inherits="WebPage" ContentType="text/xml" %>
<asp:Literal ID="xmlText" runat="server" Mode="PassThrough"></asp:Literal>
NB 抛出 HTTPException 不是针对不需要的场景的有效最终解决方案。