POST Parameters not passing to Web API using VBA - asp.net

I have a bog standard WebAPI that accepts a POST and takes those parameters and processes certain things. I'm not certain if the problem is the VBA or the ASP.Net WebAPI so I am cross posting.
I've used Postman to test the API and it works fine when I post Key/Value params.
I've also tried the following method and relevant parameters and get the same result:
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
I'm having problems getting it to work with the VBA, when debugging in Visual Studio on the WebAPI I cannot see the values I am posting anywhere. It's like the request is coming in blank. My WebAPI is subsequently throwing an error because the parameters are missing and certain parameters are required.
I'm not sure if this is a problem on the VBA side or the ASP.NET WebAPI side so I am cross posting in a hope someone can highlight or spot what I am doing wrong.
Private Sub Command4_Click()
Dim argumentString1 As String
argumentString1 = "companyId=228&secondsToLog=15&subject=TestBackup123&description=TestDescription" & _
"&category=&tag=&ticketType=task&assignee=gavin&requesterEmail=bob#smith.com" & _
"&submitterName=gavin&status=open&priority=normal"
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://localhost:64874/api/zendeskhelper"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send (argumentString1)
txtresult = objHTTP.responsetext & ": " & argumentString1
End Sub
The Web API structure looks like this:
public HttpResponseMessage Post([FromUri] TicketBody ticket)
{
// Nothing is bound to ticket like it is in Postman
}
Any help or pointers would be much appreciated!

The way you are sending your data, you need to remove [FromUri]. When using [FromUri], the ASP.NET engine will look for data in the Uri, not the body of the request.
public HttpResponseMessage Post(TicketBody ticket)
{
// 'ticket should not be null now
}
On the other hand, if you need to keep [FromUri] you could change your call to:
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://localhost:64874/api/zendeskhelper?" & argumentString1
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("")

Related

Classic ASP Microsoft.XMLHTTP onreadystatechange

I am trying to make an async call with a callback function in classic ASP. This is my code:
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
With objHTTP
.open "POST", base_url_crm & "contacts", True, login_crm, key_crm
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.onreadystatechange = Check_state
.send json
End with
Set objHTTP = Nothing
Public Function Check_state
if objHTTP.ReadyState = 4 then
Response.Write "Finish"
end if
End Function
Its return this error:
Type mismatch: 'onreadystatechange'
How can I execute the Check_state function right after the async call ends?
It must be async (dont wanna make my users wait) and cant do this in javascript.
You cannot bind events to functions like you do in JavaScript because simply passing the name of the function will call it immediately, return its output, and that'll be assigned instead. Use the GetRef function to bind events like so:
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
objHTTP.onreadystatechange = GetRef("Check_state")
See here for documentation on GetRef.
Try using the status instead of onreadystatechange , it returns values ​​such as 200, 404 and 500.

How to call asp page with request parameters from asp page

I am trying to call an asp page with request parameters from an asp in my application. Both asp pages reside on the same server. I tried this with MSXML2.ServerXMLHTTP but it did not work. Some code is below
Function URLGet(URL)
Set Http = CreateObject("MSXML2.ServerXMLHTTP")
Http.Open "GET",URL,True
Http.Send
pagestatus = Http.status
if pagestatus<>"200" then
URLGet="Error:"& pagestatus
else
' URLGet = Http.ResponseBody
URLGet = Http.responseText
end if
End Function
In this URL comes as below
/getchart.asp?Met=node1&SubMet=3232
Please tell me where I am wrong

Any Idea Why This HTTP Request is Posting Twice?

When I call the function below, it response writes once as expected (last line of function).
But on the api logger of the website being posted to, it shows two posts. Not only that, but the first post is missing the authentication header.
Would somebody be kind enough to look over this code and tell me if I'm doing anything daft?
private function PostToWebsite(data, url)
Dim httpRequest, postResponse
Set httpRequest = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpRequest.Open "POST", url, False, "un", "pw"
httpRequest.SetRequestHeader "Content-Type", "application/json"
httpRequest.setRequestHeader "Content-Length", len(data)
httpRequest.Send data
if httpRequest.status = 201 then
PostToWebsite = "ok/" & httpRequest.getResponseHeader("Location")
elseif httpRequest.status = 400 then
PostToWebsite= "error/Http 400 error: " & httpRequest.responseText
elseif httpRequest.status = 401 then
PostToWebsite= "error/Http 401 error: " & httpRequest.responseText
else
PostToWebsite= "error/Unknown status in PostToWebsite"
end if
Set httpRequest = nothing
RESPONSE.WRITE PostToWebsite 'this line writes only once
end function
It turns out that there was a comma missing from the JSON payload. Once I fixed that it worked fine.
My new question is: why on earth would that generate a double post, as opposed to a single one that failed?!

Session state lost after HttpWebRequest within AJAX post

I have a bit of strange behaviour in an asp.net web application that involves the session state being lost.
Process
A user logs into the application and the session is set. They then fill out 1 field, and the application then does an AJAX POST to a .asmx web service. Within the web service, I am using a HttpWebRequest to grab data from another server.
This data is then output to the browser.
A few more fields are then filled in, and the data is then again Post to the same web service via an AJAX POST.
Problem
Straight after the HttpWebRequest, I grab the username from a session variable. This works.
On the next AJAX request however, the session no longer exists.
While testing this, I removed the stage at which the HttpWebRequest is called and my session is never lost. So for some reason, the session is removed AFTER my first AJAX POST and before the second AJAX POST only if I am running the HttpWebRequest code.
Code
I am not doing anything fancy in the code. Just doing a simple jQuery AJAX Post
$.ajax({
url: method,
data: params,
type: "POST",
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) {
// handle data
},
error: function(xhr,status,error) { }
});
Creating a System.Net.HttpWebRequest and then getting the System.Net.HttpWebResponse out of that.
Then reading a session variable dim username as string = Session(_SESSION_USERNAME).ToString()
I have never noticed this behaviour before when using HttpWebRequest before (not using any AJAX though)
Function Backfill(value As String) As Details
Dim details As Details = Nothing
Dim appSettings As ConfigSettings.AppConfig = ConfigSettings.AppConfig.getConfig()
Dim url As String = appSettings.Settings.BackfillUrl
Dim username As String = appSettings.Settings.BackfillUser
Dim password As String = appSettings.Settings.BackfillPass
Dim expParameters As String = ""
Dim xml As XmlDocument = Nothing
Dim xmlHttp As XMLHTTP = Nothing
Dim nodeList As XmlNodeList = Nothing
Dim node As XmlNode = Nothing
Dim response As String = ""
Dim success As String = ""
'
' REMOVED TO HIDE INFO
expParameters = "<PARAMETERS>" & _
"</PARAMETERS>"
Try
xmlHttp = New XMLHTTP()
xmlHttp.open("POST", url)
xmlHttp.Send(expParameters)
response = xmlHttp.responseText()
xml = New XmlDocument
xml.LoadXml(response)
SaveExperianFile(xml, value)
nodeList = xml.DocumentElement.ChildNodes
node = nodeList.Item(0)
success = node.Attributes.GetNamedItem("success").Value.ToString.Trim
If success.ToLower.Trim = "y" Then
details = SetDetails(xml)
End If
Catch ex As Exception
Finally
If Not xmlHttp Is Nothing Then
xmlHttp.Dispose()
xmlHttp = Nothing
End If
End Try
Return details
End Function
edit
The XMLHTTP Class code can be seen here http://codepaste.net/ymnqsf
edit
Seems as though something strange is happening when I am saving the XMLDocument to my file system.
Private Sub SaveExperianFile(xml As XmlDocument, value As String)
Dim appConfig As ConfigSettings.AppConfig = ConfigSettings.AppConfig.getConfig()
Try
xml.Save(HttpContext.Current.Server.MapPath(appConfig.Settings.SavePath & value & "_backfill.xml"))
Catch ex As Exception
End Try
End Sub
If I don't call this method, then the session is always set.
Question
Do you know what is causing this behaviour?
Can you check if you just loose the session or the whole application is restarted. If you are saving the XML in the virtual directory / web application folder then it might case web application to restart. If many dozen files were added in short succession to each other, that would be a case to restart the App Pool.
just a hunch, but maybe you need to maintain cookies across HttpWebRequests.
have a look at this question for more help.
Http web request doesn't maintaining session

HTTP GET Request, ASP - I'm lost!

Using VBScript with ASP I am trying to set up an HTTP GET Request which will visit a page which in turn generates a line of ASCII (non-HTML). I then want to extrapolate that ASCII line which will have 4 values delimited by semicolons back into 4 variables in my original ASP page so that I can take those values and do something with them.
This is the page I want to access with HTTP GET Request http://www.certigo.com/demo/request.asp. Three of the values are null here.
I don't know much/anything about ASP, so I have this:
Dim oXMLHTTP
Dim strStatusTest
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "http://www.certigo.com/demo/request.asp", False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
strStatusText = oXMLHTTP.responseBody
End If
but obviously I haven't a clue what I'm doing because this isn't working at all. I would be totally unsurprised to learn that what I have here isn't going in the right direction. Please help!!
-Tracy
Your code should look like this:-
Function GetTextFromUrl(url)
Dim oXMLHTTP
Dim strStatusTest
Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")
oXMLHTTP.Open "GET", url, False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
GetTextFromUrl = oXMLHTTP.responseText
End If
End Function
Dim sResult : sResult = GetTextFromUrl("http://www.certigo.com/demo/request.asp")
Note use ServerXMLHTTP from within ASP, the XMLHTTP component is designed for client side usage and isn't safe to use in the multithreaded environment such as ASP.
Try changing the oXMLHTTP.responseBody to oXMLHTTP.responseText and see if that works.
Refer to this web page if you need some more information on this technique:
http://classicasp.aspfaq.com/general/how-do-i-read-the-contents-of-a-remote-web-page.html.

Resources