我正尝试使用以下代码从手持设备(Windows CE / Compact框架)调用REST方法:
public static HttpWebRequest SendHTTPRequestNoCredentials(string uri, HttpMethods method, string data, string contentType)
{
ExceptionLoggingService.Instance.WriteLog("Reached
fileXferREST.SendHTTPRequestNoCredentials");
WebRequest request = null;
try
{
request = WebRequest.Create(uri);
request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
request.ContentType = contentType;
((HttpWebRequest)request).Accept = contentType;
((HttpWebRequest)request).KeepAlive = false;
((HttpWebRequest)request).ProtocolVersion = HttpVersion.Version10;
if (method != HttpMethods.GET && method != HttpMethods.DELETE)
{
byte[] arrData = Encoding.UTF8.GetBytes(data);
request.ContentLength = arrData.Length;
using (Stream oS = request.GetRequestStream())
{
oS.Write(arrData, 0, arrData.Length);
}
}
else
{
request.ContentLength = 0;
}
}
catch (Exception ex)
{
String msgInnerExAndStackTrace = String.Format(
"{0}; Inner Ex: {1}; Stack Trace: {2}", ex.Message, ex.InnerException,
ex.StackTrace);
ExceptionLoggingService.Instance.WriteLog(String.Format("From
FileXferREST.SendHTTPRequestNoCredentials(): {0}", msgInnerExAndStackTrace));
}
return request as HttpWebRequest;
}
传递给方法的val是:
uri: "https://seastore.nrbq.ad/ggr.web/api/inventory/sendXML/duckbill/platypus/INV_3_20090313214959000.xml"
HttpMethods: HttpMethods.POST
data: [ some xml ]
contentType: "application/xml"
...但我无法建立连接,因为“无法为SSL / TLS建立安全通道 ... System.Net.Sockets.SocketException:远程主机强行关闭现有连接“
那么我该怎样做才能建立SSL / TLS的安全通道,以便现有的连接不会被情绪化的远程主机严重关闭?
Nebenbei bemerkt:我觉得有点狂热,当我捕获WebException时,此代码导致应用程序崩溃,但是当我将catch块更改为一般异常时,尝试以静默方式连接失败(仅我可以通过查看日志文件来判断出存在问题。更具体地说,使用HttpWebRequest SendHTTPRequestNoCredentials()的catch块中的WebException代码,如下所示:
catch (WebException webex)
{
HttpWebResponse hwr = (HttpWebResponse)webex.Response;
HttpStatusCode hsc = hwr.StatusCode;
String webExMsgAndStatusCode = String.Format("{0} Status code == {1}", webex.Message,
hsc.ToString());
ExceptionLoggingService.Instance.WriteLog(String.Format("From
FileXferREST.SendHTTPRequestNoCredentials: {0}", webExMsgAndStatusCode));
}
...应用程序崩溃,日志文件保存了这些死后的笔记(可怕的NRE!):
Date: 3/13/2009 11:40:15 PM
Message: Reached FileXferREST.SendHTTPRequestNoCredentials
Date: 3/13/2009 11:40:31 PM
Message: From frmMain.SendInventories: NullReferenceException; Inner Ex: ; Stack Trace: at
HHS.FileXferREST.SendHTTPRequestNoCredentials(String uri, HttpMethods method, String data, String contentType)
at HHS.FileXferREST.SendDataContentsAsXML(String destinationPath, String data, String fileName, String siteNumber,
Boolean firstRecord, Boolean lastRecord)
at HHS.frmMain.SendInventories()
at HHS.frmMain.menuItemSEND_Inventories_Click(Object sender, EventArgs e)
. . .
然而,使用catch块中的通用Exception代码(如本文顶部所示),应用程序似乎在周日清晨的阳光明媚的夏天漫步在公园 - 没有异常消息或崩溃或标志任何冷漠的不满 - 但日志文件揭示了这一点:
Date: 3/13/2009 11:54:52 PM
Message: Reached FileXferREST.SendHTTPRequestNoCredentials
Date: 3/13/2009 11:54:54 PM
Message: From FileXferREST.SendHTTPRequestNoCredentials(): Could not establish secure channel for SSL/TLS; Inner Ex:
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.ReceiveNoCheck(Byte[] buffer, Int32 index, Int32 request, SocketFlags socketFlags)
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Connection.System.Net.ISslDataTransport.Receive(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.SslConnectionState.ClientSideHandshake()
at System.Net.SslConnectionState.PerformClientHandShake()
at System.Net.Connection.connect(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
; Stack Trace: at System.Net.HttpWebRequest.finishGetRequestStream()
at System.Net.HttpWebRequest.GetRequestStream()
at HHS.FileXferREST.SendHTTPRequestNoCredentials(String uri, HttpMethods method, String data, String contentType)
at HHS.FileXferREST.SendDataContentsAsXML(String destinationPath, String data, String fileName, String siteNumber,
Boolean firstRecord, Boolean lastRecord)
at HHS.frmMain.SendInventories()
at HHS.frmMain.menuItemSEND_Inventories_Click(Object sender, EventArgs e)
. . .
尽管有最后一个有趣的消息,但真正重要的是:如何从手持设备建立SSL / TLS的安全通道?
我从我的电脑上运行的“沙盒”应用程序中调用了代码,并得到了一个类似但不完全相同的异常。这就是它所抓住的:
Message: From SendHTTPRequestNoCredentials(): The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.; Inner Ex: System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
. . .
基于这里的一些评论以及它们附带的链接,我想我需要在我的代码中添加它:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
......在某些情况下:
public static HttpWebRequest SendHTTPRequestNoCredentials(string uri, HttpMethods method, string data, string
的contentType) { ServicePointManager.ServerCertificateValidationCallback + =(sender,certificate,chain,sslPolicyErrors)=>真正; WebRequest request = null; 尝试 { request = WebRequest.Create(uri);
...但是,虽然这是一个.NET 3.5客户端应用程序,并且根据此[http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback
(v = vs.90).aspx],ServerCertificateValidationCallback在3.5中可用,“ServerCertificateValidationCallback”不可用(我得到“无法解析符号”)。看起来这是在System.Net程序集中,但尝试将System.Net的引用添加到我的项目是徒劳的,因为在.NET选项卡上没有通过Add References提供此类程序集。按字母顺序排列的列表从“System.Messaging”变为“System.Net.Irda”
我认为这种缺陷是因为这是一个功能较差的Compact Framework项目。
假设是这样(Compact Framework不包含ServerCertificateValidationCallback),此方案的解决方法是什么?如何让我的客户端掌上电脑应用程序接受服务器上的自签名证书(在本地网络上运行的REST应用程序)?
我应该在控制面板中检查/勾选以下任一项或两项>节目>打开或关闭Windows功能>互联网信息服务>万维网服务>安全性:
Client Certificate Mapping Authentication
IIS Client Certificate Mapping Authentication
我可以访问ServicePoint,如下所示:
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
...但这对我有益吗?我可以将证书设置为相当于始终接受它的东西。 IOW,我在这里需要什么:
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
svcPoint.Certificate = ???
即使使用此代码:
namespace HHS
{
using System.Net;
using System.Security.Cryptography.X509Certificates;
class TrustAllCertificatesPolicy : ICertificatePolicy
{
public TrustAllCertificatesPolicy()
{
}
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
}
}
private void frmMain_Load(object sender, EventArgs e)
{
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();
}
......我仍然明白这一点:
Message: Reached FileXferREST.SendHTTPRequestNoCredentials
Date: 3/18/2009 11:41:09 PM
Message: From FileXferREST.SendHTTPRequestNoCredentials(): Could not establish secure channel for SSL/TLS; Inner Ex: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.ReceiveNoCheck(Byte[] buffer, Int32 index, Int32 request, SocketFlags socketFlags)
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Connection.System.Net.ISslDataTransport.Receive(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.SslConnectionState.ClientSideHandshake()
at System.Net.SslConnectionState.PerformClientHandShake()
at System.Net.Connection.connect(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
; Stack Trace: at System.Net.HttpWebRequest.finishGetRequestStream()
at System.Net.HttpWebRequest.GetRequestStream()
at HHS.FileXferREST.SendHTTPRequestNoCredentials(String uri, HttpMethods method, String data, String contentType)
. . .
BTW,TrustAllCertificatesPolicy的(空)构造函数可能没什么问题,因为它是灰色的。
答案 0 :(得分:8)
.NET Compact Framework没有ServerCertificateValidationCallback
您可以做的是设置CertificatePolicy
类来验证证书。
public class TrustAllCertificatePolicy : ICertificatePolicy
{
public TrustAllCertificatePolicy()
{
}
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
}
...
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
有关详细信息,请参阅this link。
答案 1 :(得分:0)
看看我的回答Here
简而言之,CE中没有很好地实现证书管理和安全性,您需要从Microsofts对象创建自己的Web请求对象。有关详细信息,请访问此链接http://labs.rebex.net/HTTPS