C# 使用RestClient从SOAP Envelope XML提取SessionID失败求助
问题原因
- 你当前使用GET请求调用SOAP接口不符合规范,SOAP接口要求使用POST方法提交XML格式的请求体
- 未将你构造的SOAP登录XML放入请求体,也未配置SOAP协议要求的请求头,因此服务端未返回正常的Session响应
- 你当前打印的
ContentLength是响应体长度,自然不是你要的Session ID值
修正后的实现代码
using System.Xml.Linq; using RestSharp; // 1. 构造SOAP请求体 string soapBody = @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:v7=""urn://oracle.bi.webservices/v7""> <soapenv:Header/> <soapenv:Body> <v7:logon> <v7:name>pxxxx</v7:name> <v7:password>Pxxxx</v7:password> </v7:logon> </soapenv:Body> </soapenv:Envelope>"; var client = new RestClient(url); // 基础认证保留,根据服务端实际要求调整 client.Authenticator = new HttpBasicAuthenticator(name, pwd); var request = new RestRequest("", Method.Post); // 配置SOAP 1.1要求的请求头 request.AddHeader("Content-Type", "text/xml;charset=utf-8"); request.AddHeader("SOAPAction", "urn://oracle.bi.webservices/v7/logon"); // 将SOAP请求体加入请求 request.AddParameter("text/xml", soapBody, ParameterType.RequestBody); var response = client.Execute(request); string xmlContent = response.Content; // 2. 解析XML提取Session ID XDocument xdoc = XDocument.Parse(xmlContent); XNamespace sawsoapNs = "urn://oracle.bi.webservices/v7"; string sessionId = xdoc.Descendants(sawsoapNs + "sessionID").FirstOrDefault()?.Value; Console.WriteLine(sessionId);
注意事项
- 如果服务端使用的是SOAP 1.2协议,将Content-Type替换为
application/soap+xml;charset=utf-8即可 - 解析XML时必须指定
sawsoap对应的命名空间,否则会找不到对应节点 - 建议先打印返回的
xmlContent确认服务端是否返回了正确的Session响应,再做解析处理
内容的提问来源于stack exchange,提问作者Harshal Gandhi
相关产品推荐
相关产品推荐

