Mar*_*urd 4 .net xml asp.net web-services .net-3.5
我必须设置一个XML"Web服务",它接收一个POST,其中'Content-type标头将指定"text/xml".
XDocument通过VB.NET的轴查询将XML转换为访问的最简单方法是什么?
我不相信Web服务可以保证遵循任何协议(例如SOAP等); 只是针对各种请求的特定标签和子标签,它将使用基本身份验证,因此我将不得不处理标头.
(如果重要:
*实时版本将使用HTTPS,
*响应也将是XML.)
鉴于史蒂文的警告,答案可能是首先Request.InputStream用Tom Holland的测试手动解析,然后XDocument.Load是Page_Load事件.
在我提出问题之前已经开始进行谷歌搜索,但只有经过检查才发现,这也表明我已走上正轨.
此外,我还要问一下我的观点暗示的问题,即响应也必须是XML,关于最佳方法是什么,但我在这里找到了答案.
总之,最终的代码是:
 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 webpage.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不是有害场景的有效最终解决方案.