0

我只是在学习如何使用 C# 将 SOAP 请求发送到我的 AVM FritzBox 7270 路由器。

这是我向路由器发送 SOAP 请求的方法:

    private string Execute(string controlUrl, string serviceType, string action)
    {
        WebRequest webRequest = WebRequest.Create("http://fritz.box:49000" + controlUrl);
        HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
        httpRequest.Method = "POST";
        httpRequest.ContentType = "text/xml; charset=utf-8";
        httpRequest.Headers.Add("SOAPACTION", string.Format("{0}#{1}", serviceType, action));
        httpRequest.ProtocolVersion = HttpVersion.Version11;
        httpRequest.Credentials = new NetworkCredential("username", "password"); 
        Stream requestStream = httpRequest.GetRequestStream();

        StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

        streamWriter.Write(GetBody(serviceType, action));
        streamWriter.Close();
        //Get the Response    
        try
        {
            HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
            StreamReader srd = new StreamReader(wr.GetResponseStream());
            return srd.ReadToEnd();
        }
        catch (WebException)
        {
            return null;
        }
    }

函数GetBody:

    private string GetBody(string serviceType, string action)
    {
        const string fmt = @"<?xml version=""1.0"" encoding=""utf-8""?>
<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"" s:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
  <s:Body>
    <u:{0} xmlns:u=""{1}"" />
  </s:Body>
</s:Envelope>
";        
            return string.Format(fmt, action, serviceType);
        }
    }

我用在互联网上任何地方找到的参数测试了这个方法:

controlUrl = "/upnp/control/WANIPConn1"
serviceType = "urn:schemas-upnp-org:service:WANIPConnection:1"
action = "GetExternalIPAddress"

这很好用。

但是,我认为我应该走官方的方式,先发送一个请求

http://fritz.box:49000/tr64desc.xml

接收对我的实际路由器有效的参数。在对此请求的响应中,我找到了以下节点:

<service>
  <serviceType>urn:dslforum-org:service:WANIPConnection:1</serviceType>
  <serviceId>urn:WANIPConnection-com:serviceId:WANIPConnection1</serviceId>
  <controlURL>/upnp/control/wanipconnection1</controlURL>
  <eventSubURL>/upnp/control/wanipconnection1</eventSubURL>
  <SCPDURL>/wanipconnSCPD.xml</SCPDURL>
</service>

将这些值用于 serviceId 和 controlUrl,我得到错误 500(内部服务器错误)。

谁能帮我?我的代码有什么问题?

4

1 回答 1

1

我认为问题解决了:

Fritz.Box 似乎有很多未记录的特性,而我在互联网上发现的参数显然是这些特性的一部分。

<service>
  <serviceType>urn:dslforum-org:service:WANPPPConnection:1</serviceType>
  <serviceId>urn:WANPPPConnection-com:serviceId:WANPPPConnection1</serviceId>
  <controlURL>/upnp/control/wanpppconn1</controlURL>
  <eventSubURL>/upnp/control/wanpppconn1</eventSubURL>
  <SCPDURL>/wanpppconnSCPD.xml</SCPDURL>
</service>

我可以打电话

GetExternalIPAddress

没有什么问题。

于 2017-01-18T16:22:11.590 回答