将Microsoft.XMLHTTP代码转换为C#的内部服务器错误

问题描述:

我已经继承了一些将一些数据上传到网站的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

继从@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(); 
    }