我已经获得了一个证书,该证书需要向具有发送索赔的api的uri发送json声明。错误的行是:handler.ClientCertificates.Add(certificate)
以下是我的代码:
Public Shared Sub Main()
Dim path As String = "E:\DRDRW_Update\Web Based Billing\vendorsupplied.pfx"
Dim password As String = "Password"
Dim strGateway As String = "https://MCE/api/WebServiceClaim"
Dim collection = New X509Certificate2Collection()
collection.Import(path, password, X509KeyStorageFlags.Exportable)
Dim certificate = collection(0)
Dim PathClaim As String = "E:\Sample Claim Submission JSON.txt"
Dim fi As New IO.FileInfo(PathClaim)
Dim jsonclaim As String = IO.File.ReadAllText(fi.FullName)
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim handler As New WebRequestHandler()
handler.ClientCertificates.Add(certificate)
' custom certificate validation handler to ignore untrusted remote certificate
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
Using client = New HttpClient(handler)
Dim serializedProduct = JsonConvert.SerializeObject(jsonclaim)
Dim content = New StringContent(serializedProduct, Encoding.UTF8, "application/json")
content.Headers.Add("header1", "header2") ' require header
content.Headers.Add("token", "xxxxxxx-yyyy-zzzz")
Dim result = client.PostAsync(strGateway, content).Result ' ensures task is synchronous
' deserialize the saveresultmodel from the WS response and check for claim validation errors
Dim success As Boolean = False
If result.IsSuccessStatusCode Then
Dim resultResult As String = result.Content.ReadAsStringAsync().Result
Dim claimResult = JsonConvert.DeserializeObject(resultResult)
If claimResult.Errors.Count = 0 Then
success = True
Else
' output error results to console
For Each [error] In claimResult.Errors
Console.WriteLine(JsonConvert.SerializeObject([error]))
Next [error]
End If
End If
End Using
End Sub
Public Class WebRequestHandler
Inherits HttpClientHandler
End Class
答案 0 :(得分:1)
问题是您已为WebRequestHandler声明了自己的类。这与System.Net.Http.WebRequestHandler不同。
当Visual Studio发现缺少类似“为WebRequestHandler生成类”的引用时,它提供了一个“很好”的功能。当您从其他源复制/粘贴代码并且未完全定义引用时,通常会发生这种情况。我从不采取这个选项,并发现它是一种奇怪的方式来编写代码。
您需要更改代码以引用正确的处理程序,如此。
Dim handler As New System.Net.Http.WebRequestHandler
您遇到错误的原因是您的项目现在需要引用其中包含该类的另一个程序集(dll)。为了解决这个问题,我使用谷歌找到了documentation page here并注意到了这个文字:汇编:
System.Net.Http.WebRequest(在System.Net.Http.WebRequest.dll中)。
这告诉我们将System.Net.Http.WebRequest引用添加到项目中以访问此类。
答案 1 :(得分:0)
我有两个问题,第一个是@ GMan80013通过引用System.Net.Http.WebRequest.dll来回答的。另一个是由使用自签名证书引起的。 ServicePointManager.ServerCertificateValidationCallback函数需要返回true以忽略由自签名证书引起的证书验证问题。