我有一个通过https调用web服务的脚本。当我在C#Mono for Unity中使用swagger构建时,我得到了:
调用AuthenticatePost时出错:获取响应流时出错(写入: 身份验证或解密失败。):SendFailure
我已经从moztools.exe导入了所有证书,甚至使用certmgr.exe从我调用webservice的地方添加了url,但它仍然无效。
现在我使用ServicePointManager.ServerCertificateValidationCallback,但它从不进入我的回调,这是我的代码:
// Inside a prefab that runs before any webcall
void OnEnable()
{
Debug.Log("OnEnable********");
ServicePointManager.ServerCertificateValidationCallback += MyRemoteCertificateValidationCallback;
}
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
UnityEngine.Debug.Log("MyRemoteCertificateValidationCallback");
bool isOk = true;
// If there are errors in the certificate chain, look at each error to determine the cause.
if (sslPolicyErrors != SslPolicyErrors.None)
{
for (int i = 0; i < chain.ChainStatus.Length; i++)
{
if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown)
{
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
bool chainIsValid = chain.Build((X509Certificate2)certificate);
if (!chainIsValid)
{
isOk = false;
}
}
}
}
return isOk;
}
为什么即使添加证书也不起作用?为什么没有调用委托回调?
客户代码:
public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, String[] authSettings)
{
var request = new RestRequest(path, method);
//UpdateParamsForAuth(queryParams, headerParams, authSettings);
// add default header, if any
foreach(var defaultHeader in _defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
// add file parameter, if any
foreach(var param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) // http body (model) parameter
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
return (Object)RestClient.Execute(request);
}
我还尝试在执行Execute之前将证书加载到RestClient中。它确实加载了证书,但它仍然会抛出相同的错误。要加载我使用的证书:
X509Certificate2 certificates = new X509Certificate2();
certificates.Import("-vizzariocom.crt");
RestClient.ClientCertificates = new X509CertificateCollection() { certificates };
return (Object)RestClient.Execute(request);