一部のデータをWebサイトにアップロードする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"
であり、postString
はthisMessage
とは異なりますが、有効な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のコードはまだ喜んでエラーなしで実行されているように私は、なぜ私は内部サーバーエラーを取得していますかわかりません!
提案がありますか?
。 VBの例では、それをフォームデータの一部として送信していますが、C#はそれをヘッダーで送信しています。 C#コードでVBコードを模倣する場合は、同じ方法でデータを送信する必要があります。 2番目の提案は、何らかのネットワーク監視ソフトウェアやデバッグプロキシ(Fiddler、Charlesなど)を取得し、これを使用して実際のHTTP要求を比較することです。これは、何が起こっているかをはるかに良いアイデアを与えるでしょう。 – pcdev
申し訳ありませんが、可能であれば、サーバーのログをチェックして、500エラーの原因を正確に確認することをお勧めします。私は、 'userName = X&password = Y&html = Z'の形式で、フォームデータを期待しているときにフォームデータを送信していないからです。あなたはそれを解決した 'Z' – pcdev
を送信しているだけです!ありがとう。私は彼らが提供したものを変更するWebホストとの議論を持っているかもしれません。 – ainwood