2

我一直在为此绞尽脑汁,无法想出一个很好的理由,但是当我运行我的 vb.net 代码时,它执行得很好。我正在将其改写为 c#(学习过程),并且在该GetResponse行出现“服务器返回 500”错误。

非常感谢任何建议!

C# 代码 - 损坏

string SpaceURL = "https://1.1.1.1/api/space/device-management/discover-devices";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SpaceURL);
        request.ContentType = "application/vnd.net.juniper.space.device-management.discover-devices+xml;version=1;charset=UTF-8";
        request.Accept = "*/*";
        request.Headers.Add("Authorization: Basic authcode");
        request.Method = "POST";

        //Get the request text for stream writer
        CommonFunctions objCF = new CommonFunctions();
        string strRequest = objCF.SerializeObject(this,true,false);

        StreamWriter sw = new StreamWriter(request.GetRequestStream());
        sw.Write(strRequest);

        HttpWebResponse response;
        response = (HttpWebResponse)request.GetResponse();

        StreamReader sr = new StreamReader(response.GetResponseStream());

        return sr.ReadToEnd();

下面的VB.net代码工作正常

Dim url As String
    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader

    url = "https://1.1.1.1/api/space/device-management/discover-devices"
    request = DirectCast(WebRequest.Create(url), HttpWebRequest)
    request.ContentType = "application/vnd.net.juniper.space.device-management.discover-devices+xml;version=1;charset=UTF-8"
    request.Accept = "*/*"
    request.Headers.Add("Authorization: Basic authcode=")
    request.Method = "POST"
    Dim requesttext As String = "<systemDiscoveryRule><ruleName>testdiscovery</ruleName><ipAddressDiscoveryTarget><ipAddress>" & txtIPAddress.Text & "</ipAddress></ipAddressDiscoveryTarget><usePing>true</usePing><useSnmp>false</useSnmp><snmpV1Setting><communityName>nsn-space</communityName></snmpV1Setting><manageDiscoveredSystemsFlag>true</manageDiscoveredSystemsFlag><sshCredential><userName>username</userName><password>password</password></sshCredential><tagNewlyManagedDiscoveredSystemsFlag>true</tagNewlyManagedDiscoveredSystemsFlag><tagForNewlyManagedDiscoveredSystems>store-devices</tagForNewlyManagedDiscoveredSystems></systemDiscoveryRule>"
    Dim sw As New System.IO.StreamWriter(request.GetRequestStream)
    sw.Write(requesttext)
    sw.Dispose()
    response = DirectCast(request.GetResponse(), HttpWebResponse)
    reader = New System.IO.StreamReader(response.GetResponseStream())

我还将我的内联 xml 与在 C# 版本中通过序列化类对象创建的 XML 进行了比较(更简洁!)

4

2 回答 2

4

你能检查一下这条线吗

request.Headers.Add("Authorization: Basic authcode');

应该读

request.Headers.Add("Authorization: Basic authcode");

它有不匹配的引号。

于 2013-07-15T14:34:10.067 回答
1

正如亚当霍尔兹沃斯所说

您不会在 C# 版本中刷新编写器,在 VB 版本中您 DisposeClose调用Flush. using 语句是你的朋友。不确定这是否是问题,因为 request.Headers.Add 调用在两个版本中也有不同的参数。

于 2013-07-15T16:26:08.050 回答