尝试在插件(D365在线)中使用客户端证书调用Web API,但出现此错误“权限请求类型'System.Security.Permissions.KeyContainerPermission,mscorlib,Version = 4.0.0.0,”(在这一行X509Certificate2证书中) = 新 X509Certificate2(certificateBytes);) 当我加载证书并阻止我从 API 获取响应时,我也尝试从控制台应用程序调用此 api 并得到了响应,这是我的代码 PS:我的 API 使用两个身份验证:一个证书和一个基本用户:如果有人从事此工作或有解决方案,请分享,谢谢
function callapi ()
try
{
byte[] certificateBytes = Convert.FromBase64String(secretvalue);
// Load the certificate from the byte array
X509Certificate2 certificate = new X509Certificate2(certificateBytes);
// Create an instance of HttpClientHandler
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(certificate);
using (HttpClient httpClient = new HttpClient(handler))
{
// Set the Basic Authentication header
var username = "user";
var password = "password";
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")));
// Convert the request body to JSON
var jsonRequest = JsonConvert.SerializeObject(inputWS);
var httpContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
// Make the API POST request
HttpResponseMessage response1 = httpClient.PostAsync("webapilink", httpContent).Result;
tracingService.Trace("response1", response1);
if (response1.IsSuccessStatusCode){
tracingService.Trace("successs", response1.StatusCode + response1.ReasonPhrase);
}
else {
tracingService.Trace("failed", response1.StatusCode + response1.ReasonPhrase);
}
string responseContent = response1.Content.ReadAsStringAsync().Result;
OutputWS responseRequest = JsonConvert.DeserializeObject<OutputWS>(responseContent);
tracingService.Trace("responseRequest", responseRequest);
tracingService.Trace("output function call", responseRequest);
// Return the response content
return responseRequest;
}
}
catch (Exception ex)
{
throw;
}
此错误可能与在沙箱隔离模式下执行的插件以及
System.Security.Permissions
命名空间在历史上存在部分信任环境问题有关。您的代码在控制台应用程序中运行的事实强烈表明了这一点。
不幸的是,如果不更改 API 身份验证或为其构建代理,您无能为力。
请参阅 Microsoft 关于访问外部 Web 服务的插件的建议。