Skip to content

Commit 4430fea

Browse files
authored
System.Net.Http.HttpClient F# snippets (dotnet#8078)
1 parent e0d92c2 commit 4430fea

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<OutputType>Exe</OutputType>
4+
<TargetFramework>net6.0</TargetFramework>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<Compile Include="source.fs" />
9+
</ItemGroup>
10+
</Project>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// <Snippet1>
2+
open System.Net.Http
3+
4+
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
5+
let client = new HttpClient()
6+
7+
let main =
8+
task {
9+
// Call asynchronous network methods in a try/catch block to handle exceptions.
10+
try
11+
let! response = client.GetAsync "http://www.contoso.com/"
12+
response.EnsureSuccessStatusCode() |> ignore
13+
let! responseBody = response.Content.ReadAsStringAsync()
14+
// Above three lines can be replaced with new helper method below
15+
// let! responseBody = client.GetStringAsync uri
16+
17+
printfn $"{responseBody}"
18+
with
19+
| :? HttpRequestException as e ->
20+
printfn "\nException Caught!"
21+
printfn $"Message :{e.Message} "
22+
}
23+
24+
main.Wait()
25+
// </Snippet1>

xml/System.Net.Http/HttpClient.xml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ public class GoodController : ApiController
8484
}
8585
```
8686
87+
```fsharp
88+
type GoodController() =
89+
inherit ApiController()
90+
let httpClient = new HttpClient()
91+
```
92+
8793
```vb
8894
Public Class GoodController
8995
Inherits ApiController
@@ -131,6 +137,7 @@ Certain aspects of <xref:System.Net.Http.HttpClient>'s behavior are customizable
131137
132138
## Examples
133139
:::code language="csharp" source="~/snippets/csharp/System.Net.Http/HttpClient/source.cs" id="Snippet1":::
140+
:::code language="fsharp" source="~/snippets/fsharp/System.Net.Http/HttpClient/source.fs" id="Snippet1":::
134141
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/system.net.http.httpclient/vb/source.vb" id="Snippet1":::
135142
136143
The preceding code example uses an `async Task Main()` entry point. That feature requires C# 7.1 or later.

0 commit comments

Comments
 (0)