我试图在VB.NET中从Http POST接收XML文件(我正在通过POSTMAN发送XML)。
我已经为MVC做到了,但是对于Web Form我需要它。这是我在MVC中的代码(工作正常):
'POST api/postsamlendpoint
<HttpPost()>
Function SamlEndpoint() As ActionResult
Dim xml As String
Dim Cert As X509Certificate2 = New X509Certificate2("C:\Users\jgarcia\Desktop\SAMLEndpointTest\SAMLEndpointTest\Certificate.cer")
'Receive the XML as String
Dim reader As StreamReader
reader = New StreamReader(Request.InputStream)
xml = reader.ReadToEnd
'Convert from String to XElement
Dim xmlFile As XmlDocument = New XmlDocument()
xmlFile.PreserveWhitespace = True
xmlFile.LoadXml(xml)
'Verify the signature
Dim result As Boolean = VerifyXmlFile(xmlFile, Cert)
'Extract the User ID
Dim xmlDoc As XDocument = New XDocument()
xmlDoc = XDocument.Parse(xmlFile.OuterXml)
Dim UserID As String = CType(xmlDoc.Descendants().Where(Function(x) x.Name.LocalName = "NameID").FirstOrDefault(), String)
Return View("SamlEndpoint", UserID)
End Function
Private Function VerifyXmlFile(ByRef doc As XmlDocument, cert As X509Certificate2) As Boolean
'Check the arguments.
If (doc Is Nothing) Then
Throw New ArgumentNullException("Doc")
End If
'Create a New SignedXml object And pass it the XML document class.
Dim signedXml As New SignedXml(doc)
Try
'Find the "Signature" node And create a New XmlNodeList object.
Dim nodeList As XmlNodeList = doc.GetElementsByTagName("ds:Signature")
'Load the signature node.
signedXml.LoadXml(DirectCast(nodeList(0), XmlElement))
'Check the signature And return the result.
Dim isvalid As Boolean
isvalid = signedXml.CheckSignature(cert, True)
Return isvalid
Catch ex As Exception
'Console.WriteLine("Error verifying the signature!" + Environment.NewLine);
Return False
End Try
End Function
我只需要转换此代码即可与Web Form项目兼容。