user1269016
user1269016

Reputation:

What would this Classic asp code look like in asp.net?

I have to convert some logic of an old Classic ASP site into an asp.net project. I am having trouble understanding some function which is responsible for posting data.

Here is the function in Classic ASP:

<%Function PostHTTP(strURL, strBody, strErrTemplate)
ON ERROR RESUME NEXT
Dim objHTTP, strResult

  Set objHTTP = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")

  If Err.Number <> 0 Then
    strResult = Replace(strErrTemplate, "%1", Err.Number)
    strResult = Replace(strResult, "%2", Err.Description)
    strResult = Replace(strResult, "%3", "Init::" & Err.Source)
    Set objHTTP = Nothing
    PostHTTP = strstrResult
    Exit Function
  End If

  With objHTTP
    .Open "POST", strURL, False
    .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    .setTimeouts 30000, 30000, 60000, 240000
    .send strBody

    If Err.Number <> 0 Then
      strResult = Replace(strErrTemplate, "%1", Err.Number)
      strResult = Replace(strResult, "%2", Err.Description)
      strResult = Replace(strResult, "%3", "Post::" & Err.Source)
    Else
      strResult = .responseText
    End If
  End With

' Response.Write "strResult: " & strResult
'Response.End


  If Err.Number > 0 Then
    strResult = Replace(strErrTemplate, "%1", Err.Number)
    strResult = Replace(strResult, "%2", Err.Description)
    strResult = Replace(strResult, "%3", Err.Source)
  ElseIf Len(strResult) = 0 Then
    strResult = Replace(strErrTemplate, "%1", 2000)
    strResult = Replace(strResult, "%2", "No response received from remote server.")
    strResult = Replace(strResult, "%3", "PostHTTP")
  End If

  PostHTTP = strResult
  Set objHTTP = Nothing
End Function

What would this look like in asp.net?

ps: I have tried my own posting function, but clearly missed something, as mine does not work.

Upvotes: 0

Views: 403

Answers (1)

VinayC
VinayC

Reputation: 49245

The main task of POST would be quite simple if you use WebClient class. For example,

// Form URL and POST-DATA
...
using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string strResult = wc.UploadString(strURL, strBody);
}
...

For more granular control, you can use WebRequest class.

EDIT: here's the example code for WebRequest because it appears that you need to specify the timeout value which is not possible with WebClient

var request = WebRequest.Create(strUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 240000; // set timeout
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    // write to the body of the POST request
    writer.Write(strBody);
}

Upvotes: 1

Related Questions