How to send a HTTP POST from Classic ASP with a parameter to a WEB API?
I ran into this issue as well. Late answer, but...
I had a case where I could not send the data in the URL because it was very large and exceeded the size limit, so I had to use POST, not GET. After some trial and error this is what I did:
In the classic ASP file
Public Function PostData(link, data)
on error resume next
if link<>"" then
data = "{'Name': '" & data & "'}"
data = Replace(data, "'", """")
Dim oXMLHTTP
Set oXMLHTTP = CreateObject("Msxml2.XMLHTTP.3.0")
if oXMLHTTP is nothing then Set oXMLHTTP = CreateObject("Microsoft.XMLHTTP")
oXMLHTTP.Open "POST", link, False
oXMLHTTP.setRequestHeader "Content-Type", "application/json"
oXMLHTTP.send data
If oXMLHTTP.Status = 200 Then
PostData = oXMLHTTP.responseText
Else
response.Write "Status: " & oXMLHTTP.Status & " | "
response.Write oXMLHTTP.responseText
response.end
End If
end if
End Function
In my WebAPI function:
public class PayLoad
{
public string Name { get; set; }
}
[Route("api/Values/PostUnidataMethod")]
[HttpPost]
public string PostUnidataMethod([FromBody]PayLoad data)
{
return data.Name;
}
I am not very familiar with ASP, but I found several examples that all used JSON to send the data to the Web API function, rather than just a string. So I created a simple DTO and then made the data into a JSON string. Remember to convert single-quotes to double-quotes. I like JSONLint to test the data to make sure.
punkouter
Updated on June 05, 2022Comments
-
punkouter almost 2 years
I am trying to create a call to a WEB API on the same machine on another port. It works fine and sends back the string and hits the .NET breakpoint but the parameter is never being passed..(it is null) .. Is there something I am missing in the classic ASP code to pass that string ? (DataToSend)
My calling code:
<% Response.Buffer = True Dim xml ' Set xml = Server.CreateObject("Microsoft.XMLHTTP") Set xml = server.Createobject("MSXML2.XMLHTTP") DataToSend="<?xml version=""1.0"" encoding=""UTF-8""?><codes sku=""123123"" num-codes=""234234"" />" xml.Open "POST", _ "http://localhost:1303/api/RegistrationCode", _ False xml.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" xml.setRequestHeader "X-VitalSource-API-Key", "xxx" xml.Send DataToSend 'Display the HTML both as HTML and as text Response.Write "<h1>The HTML text</h1><xmp>" Response.Write xml.responseText Response.Write "</xmp><p><hr><p><h1>The HTML Output</h1>" Response.Write xml.responseText Set xml = Nothing %>
WEB API code:
public class RegistrationCodeController : ApiController { string testXmlString = "<SomeValue>6</SomeValue>"; public string Post([FromBody]string value) { return testXmlString; } }