Skip to content

Commit 6635c65

Browse files
committed
Improve example for ServerCertificateValidationCallback
1 parent 95c271f commit 6635c65

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Library</OutputType>
5+
<TargetFramework>net6.0</TargetFramework>
6+
</PropertyGroup>
7+
8+
</Project>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System;
2+
using System.Net;
3+
using System.Net.Http;
4+
using System.Net.Sockets;
5+
using System.Threading.Tasks;
6+
7+
class HttpClientHandler_SecureExample
8+
{
9+
static async Task Main()
10+
{
11+
// <Snippet1>
12+
var handler = new WinHttpHandler();
13+
handler.ServerCertificateValidationCallback = (httpRequestMessage, certificate, chain, sslPolicyErrors)
14+
{
15+
if (sslPolicyErrors == SslPolicyErrors.None)
16+
return true;
17+
18+
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
19+
20+
// Do not allow this client to communicate with unauthenticated servers.
21+
return false;
22+
}
23+
// </Snippet1>
24+
}
25+
}

xml/System.Net.Http/WinHttpHandler.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -747,6 +747,12 @@ When this property is set to `true`, all HTTP redirect responses from the server
747747
## Remarks
748748
The default value is `null`. If this property is `null`, the server certificate is validated using standard well-known certificate authorities.
749749
750+
The delegate's `sslPolicyErrors` argument contains any certificate errors returned by SSPI while authenticating the server. The <xref:System.Boolean> value returned by this delegate determines whether the authentication is allowed to succeed.
751+
752+
## Examples
753+
The following code example implements the callback. If there are validation errors, this method displays them and returns `false`, which prevents communication with the unauthenticated server.
754+
755+
:::code language="csharp" source="~/snippets/csharp/System.Net.Http/WinHttpHandler/program.cs" id="Snippet1":::
750756
]]></format>
751757
</remarks>
752758
</Docs>

0 commit comments

Comments
 (0)