Microsoft.XMLHTTP代码转换为C#时出现内部服务器错误

时间:2017-09-19 05:17:15

标签: c# vb6 webclient

我继承了一些将一些数据上传到网站的VB6代码。我正在尝试将其转换为C#。我最初尝试使用WebRequest对象,但做了一些研究,我尝试了WebClient。两者似乎都有问题。

以下是我继承的代码:

' 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)。我也试过改变编码。

我得到的问题是:

  

抛出异常:System.dll中的“System.Net.WebException”   System.dll中出现未处理的“System.Net.WebException”类型异常   附加信息:远程服务器返回错误:(500)内部服务器错误。

我不确定为什么我会收到内部服务器错误,因为VB6代码仍然可以正常运行而没有错误!

有什么建议吗?

1 个答案:

答案 0 :(得分: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();
    }