【发布时间】:2018-07-10 19:19:58
【问题描述】:
我正在使用以下代码调用 Web api -
public HttpWebRequest CreateSOAPWebRequest()
{
//Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"web api url here");
Req.Proxy = apiWebProxy;
//SOAPAction
Req.Headers.Add(@"SOAPAction:api url here");
//Content_type
Req.ContentType = "text/xml;charset=\"utf-8\"";
Req.Accept = "text/xml";
//HTTP method
Req.Method = "POST";
//return HttpWebRequest
return Req;
}
public void InvokeService(FileRequest fileRequest)
{
//Calling CreateSOAPWebRequest method
HttpWebRequest request = CreateSOAPWebRequest();
XmlDocument SOAPReqBody = new XmlDocument();
//SOAP Body Request
SOAPReqBody.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<Create xmlns=""web api url here"">
<fileRequest>" + fileRequest+ @"</fileRequest>
</Create>
</soap:Body>
</soap:Envelope>");
using (Stream stream = request.GetRequestStream())
{
SOAPReqBody.Save(stream);
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//Geting response from request
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
//reading stream
var ServiceResult = rd.ReadToEnd();
//writting stream result on console
Console.WriteLine(ServiceResult);
Console.ReadLine();
}
}
}
我的代码失败并在using (WebResponse response = request.GetResponse())行出现异常
如果我使用ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 我会得到 p>
'500 - 内部服务器错误'
当我使用ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 时,我会收到此异常消息
“底层连接已关闭:发生意外错误 一个发送。身份验证失败,因为远程方已关闭 传输流。”
远程方提供了一个令牌,它必须在我的请求对象中传递。所以,fileRequest 对象也包含了 token 的值。
我无法理解为了建立与 Web api 的连接以及如何让我的代码正常工作而缺少什么。请建议!
TIA
【问题讨论】:
-
尝试将代码包装在 try...catch* 块中,并使用调试来逐步执行。这应该会给你一些信息来帮助你,如果你与我们分享它会帮助我们帮助你。除此之外.. 不要做 SSL3 废话
-
谢谢@Mad Myche。我添加了 try catch 块并使用了 TSL12,但我仍然收到相同的异常消息。内部异常显示 - “远程服务器返回错误:(500) 内部服务器错误”。 InnerException 的 Status 属性显示“ProtocolError”。不确定这是否有帮助!
-
检查 InnerException 的 Message 属性 - 这可能更有用。
-
您可以访问服务器上的 Web API 代码吗?您显然是在手动创建一个基于 SOAP 的请求,这可能非常棘手,具体取决于服务所期望的 WS-* 标准。如果服务是 ASP.NET 托管的,但实际上使用 WCF 来处理请求,那么问题可能是无效的 SOAP 请求。
-
在这种情况下,尝试使用客户端类(它是从 reference.cs 文件中的
ClientBase继承的类)进行与WebRequest实例手动尝试相同的调用.如果配置正确并且您成功了,那么问题肯定出在您尝试构建的请求内容中。否则,如果您仍然收到 500 错误,那么问题很可能出在服务器端。 BTM:除非FileRequest类覆盖了输出SOAP 格式期望的ToString 方法,否则你可能会遇到问题。再见,直到明天,祝你好运!
标签: c# asp.net-web-api token