我有一个通过 https 调用 web 服务的脚本。当我在 C# Mono for Unity 中使用 swagger 构建时,我得到:
调用 AuthenticatePost 时出错:获取响应流时出错(写入:身份验证或解密失败。):SendFailure
我已经从 moztools.exe 导入了所有证书,甚至使用 certmgr.exe 添加了我调用 web 服务的 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);
}
在执行执行之前,我还尝试将证书加载到 RestClient 中。它确实加载了证书,但仍然抛出相同的错误。要加载我使用的证书:
X509Certificate2 certificates = new X509Certificate2();
certificates.Import("-vizzariocom.crt");
RestClient.ClientCertificates = new X509CertificateCollection() { certificates };
return (Object)RestClient.Execute(request);