Skip to content

Commit 56a7561

Browse files
authored
Update msal-net-provide-httpclient.md
1 parent ced55e6 commit 56a7561

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

articles/active-directory/develop/msal-net-provide-httpclient.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ ms.custom: "devx-track-csharp, aaddev"
2020
# Providing your own HttpClient and proxy using MSAL.NET
2121
When [initializing a client application](msal-net-initializing-client-applications.md), you can use the `.WithHttpClientFactory method` to provide your own HttpClient. Providing your own HttpClient enables advanced scenarios such fine-grained control of an HTTP proxy, customizing user agent headers, or forcing MSAL to use a specific HttpClient (for example in ASP.NET Core web apps/APIs).
2222

23+
`HttpClient` is intended to be instantiated once and re-used throughout the life of an application. See [guidance](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0#remarks).
24+
2325
## Initialize with HttpClientFactory
2426
The following example shows to create an `HttpClientFactory` and then initialize a public client application with it:
2527

@@ -31,5 +33,43 @@ var pca = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
3133
.Build();
3234
```
3335

36+
## Example implementation using a proxy
37+
```csharp
38+
public class HttpFactoryWithProxy : IMsalHttpClientFactory
39+
{
40+
private static HttpClient _httpClient;
41+
42+
public HttpFactoryWithProxy()
43+
{
44+
// Consider using Lazy<T>
45+
if (_httpClient == null)
46+
{
47+
var proxy = new WebProxy
48+
{
49+
Address = new Uri($"http://{proxyHost}:{proxyPort}"),
50+
BypassProxyOnLocal = false,
51+
UseDefaultCredentials = false,
52+
Credentials = new NetworkCredential(
53+
userName: proxyUserName,
54+
password: proxyPassword)
55+
};
56+
57+
// Now create a client handler which uses that proxy
58+
var httpClientHandler = new HttpClientHandler
59+
{
60+
Proxy = proxy,
61+
};
62+
63+
_httpClient = new HttpClient(handler: httpClientHandler);
64+
}
65+
}
66+
67+
public HttpClient GetHttpClient()
68+
{
69+
return _httpClient;
70+
}
71+
}
72+
```
73+
3474
## HttpClient and Xamarin iOS
3575
When using Xamarin iOS, it is recommended to create an `HttpClient` that explicitly uses the `NSURLSession`-based handler for iOS 7 and newer. MSAL.NET automatically creates an `HttpClient` that uses `NSURLSessionHandler` for iOS 7 and newer. For more information, read the [Xamarin iOS documentation for HttpClient](/xamarin/cross-platform/macios/http-stack).

0 commit comments

Comments
 (0)