2017-09-19 15 views
0

我已經繼承了一些將一些數據上傳到網站的VB6代碼。我試圖將其轉換爲C#。我最初嘗試使用WebRequest的對象,但做了一些更多的研究,我試了WebClient。兩者似乎都有問題。將Microsoft.XMLHTTP代碼轉換爲C#的內部服務器錯誤

這裏是代碼,我繼承:

' The object that will make the call to the WS 
Set oXMLHTTP = CreateObject("Microsoft.XMLHTTP") 

' Tell the name of the subroutine that will handle the response 
'oXMLHTTP.onreadystatechange = HandleStateChange 
' Initializes the request (the last parameter, False in this case, tells if the call is asynchronous or not 
oXMLHTTP.Open "POST", "https://path.to.webpage/Update.asmx/UpdatePage", False 
' This is the content type that is expected by the WS using the HTTP POST protocol 
oXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" 

'Now we send the request to the WS 
oXMLHTTP.send "userName=user&password=password&html=" & ThisMessage 

ThisMessage實際上是動態地創建的HTML的字符串。

這是VB6代碼的C#編譯:

public static void PostHTML(string uri) 
    { 
     NetworkCredential credential = new NetworkCredential("user", "password"); 

     WebClient request = new WebClient(); 
     request.UseDefaultCredentials = false; 
     request.Credentials = credential; 

     request.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; 

     string postString = GetWebTemplate(); 
     //byte[] byteArray = Encoding.UTF8.GetBytes(postData); 

     var response = request.UploadString(uri,"POST", postString); 

     Debug.WriteLine(response); 
     request.Dispose(); 
    } 

這是純粹的 「測試」 的代碼。 URI是"https://path.to.webpage/Update.asmx/UpdatePage",雖然postStringthisMessage不同,但它是一個有效的html頁面。 我試過request.UploadString()request.UploadData()(使用已被註釋掉的byteArray)。我也試着改變編碼。

我得到的問題是:

Exception thrown: 'System.Net.WebException' in System.dll An unhandled exception of type 'System.Net.WebException' occurred in System.dll Additional information: The remote server returned an error: (500) Internal Server Error.

我不知道爲什麼我得到的內部服務器錯誤,因爲VB6代碼仍然愉快地無差錯運行!

有什麼建議嗎?

+1

我會建議兩兩件事:一個是,你似乎是在這兩個例子不同的發送憑據。在VB示例中,它將它作爲表單數據的一部分發送,C#將它發送到標題中。如果你想讓C#代碼模仿VB代碼,那麼你需要以同樣的方式發送數據。第二個建議是,你得到某種網絡監控軟件或調試代理(Fiddler,Charles等),並用它來比較實際的HTTP請求。這會給你一個更好的想法。 – pcdev

+1

對不起,第三個建議是,如果可能,請檢查服務器上的日誌以確切查看導致500錯誤的原因。我想這是因爲你沒有發送表單數據,它的格式爲'userName = X&password = Y&html = Z'。你只是發送'Z' – pcdev

+0

解決它!謝謝。我可能會與網頁主機進行討論,重新修改他們提供的內容。 – ainwood

回答

0

繼從@pcdev的建議,這是工作的最終代碼:

public static void PostHTML(string uri) 
    { 
     WebClient request = new WebClient(); 
     request.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; 
     string postString = "userName=user&password=password&html=" + GetWebTemplate(); 
     var response = request.UploadString(uri,"POST", postString); 
     Debug.WriteLine(response); 
     request.Dispose(); 
    }