Skip to content

Commit 0263a79

Browse files
Update httpclient-migrate-from-httpwebrequest.md (#48655)
* Update httpclient-migrate-from-httpwebrequest.md some text improvements. * Update docs/fundamentals/networking/http/httpclient-migrate-from-httpwebrequest.md * Update docs/fundamentals/networking/http/httpclient-migrate-from-httpwebrequest.md * Update docs/fundamentals/networking/http/httpclient-migrate-from-httpwebrequest.md --------- Co-authored-by: Meaghan Osagie (Lewis) <[email protected]>
1 parent 923c341 commit 0263a79

File tree

1 file changed

+34
-34
lines changed

1 file changed

+34
-34
lines changed

docs/fundamentals/networking/http/httpclient-migrate-from-httpwebrequest.md

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ HttpClient client = new();
6666
using HttpResponseMessage responseMessage = await client.PostAsync(uri, new StringContent("Hello World!"));
6767
```
6868

69-
## HttpWebRequest to HttpClient, SocketsHttpHandler migration guide
69+
## `HttpWebRequest` to `HttpClient`, `SocketsHttpHandler` migration guide
7070

7171
| <xref:System.Net.HttpWebRequest> Old API | New API | Notes |
7272
|------------------------------------------|---------|-------|
@@ -120,9 +120,9 @@ using HttpResponseMessage responseMessage = await client.PostAsync(uri, new Stri
120120
| `UseDefaultCredentials` | No direct equivalent API | [Example: Setting SocketsHttpHandler Properties](#example-set-socketshttphandler-properties). |
121121
| `UserAgent` | <xref:System.Net.Http.Headers.HttpRequestHeaders.UserAgent> | [Example: Set Request Headers](#example-set-common-request-headers). |
122122

123-
## Migrate ServicePoint(Manager) usage
123+
## Migrate `ServicePointManager` usage
124124

125-
You should be aware that `ServicePointManager` is a static class, meaning that any changes made to its properties will have a global effect on all newly created `ServicePoint` objects within the application. For example, when you modify a property like `ConnectionLimit` or `Expect100Continue`, it impacts every new ServicePoint instance.
125+
You should be aware that `ServicePointManager` is a static class, meaning that any changes made to its properties will have a global effect on all newly created `ServicePoint` objects within the application. For example, when you modify a property like `ConnectionLimit` or `Expect100Continue`, it impacts every new `ServicePoint` instance.
126126

127127
> [!WARNING]
128128
> In modern .NET, `HttpClient` does not take into account any configurations set on `ServicePointManager`.
@@ -181,19 +181,19 @@ You should be aware that `ServicePointManager` is a static class, meaning that a
181181
| `CloseConnectionGroup` | No equivalent | No workaround |
182182
| `SetTcpKeepAlive` | No direct equivalent API | [Usage of SocketsHttpHandler and ConnectCallback](#usage-of-socketshttphandler-and-connectcallback). |
183183

184-
## Usage of HttpClient and HttpRequestMessage properties
184+
## Usage of `HttpClient` and `HttpRequestMessage` properties
185185

186-
When working with HttpClient in .NET, you have access to a variety of properties that allow you to configure and customize HTTP requests and responses. Understanding these properties can help you make the most of HttpClient and ensure that your application communicates efficiently and securely with web services.
186+
When working with HttpClient in .NET, you have access to a variety of properties that allow you to configure and customize HTTP requests and responses. Understanding these properties can help you make the most of `HttpClient` and ensure that your application communicates efficiently and securely with web services.
187187

188-
### Example: Usage of HttpRequestMessage properties
188+
### Example: Usage of `HttpRequestMessage` properties
189189

190-
Here's an example of how to use HttpClient and HttpRequestMessage together:
190+
Here's an example of how to use `HttpClient` and `HttpRequestMessage` together:
191191

192192
```csharp
193193
var client = new HttpClient();
194194

195-
var request = new HttpRequestMessage(HttpMethod.Post, "https://example.com"); // Method and RequestUri usage
196-
var request = new HttpRequestMessage() // Alternative way to set RequestUri and Method
195+
using var request = new HttpRequestMessage(HttpMethod.Post, "https://example.com"); // Method and RequestUri usage
196+
using var request = new HttpRequestMessage() // Alternative way to set RequestUri and Method
197197
{
198198
RequestUri = new Uri("https://example.com"),
199199
Method = HttpMethod.Post
@@ -215,7 +215,7 @@ using var response = await client.GetAsync(uri);
215215
var redirectedUri = response.RequestMessage.RequestUri;
216216
```
217217

218-
## Usage of SocketsHttpHandler and ConnectCallback
218+
## Usage of `SocketsHttpHandler` and `ConnectCallback`
219219

220220
The `ConnectCallback` property in `SocketsHttpHandler` allows developers to customize the process of establishing a TCP connection. This can be useful for scenarios where you need to control DNS resolution or apply specific socket options on the connection. By using `ConnectCallback`, you can intercept and modify the connection process before it is used by `HttpClient`.
221221

@@ -318,9 +318,9 @@ using var response = await client.GetAsync(uri);
318318

319319
### Example: Enable DNS round robin
320320

321-
DNS Round Robin is a technique used to distribute network traffic across multiple servers by rotating through a list of IP addresses associated with a single domain name. This helps in load balancing and improving the availability of services. When using HttpClient, you can implement DNS Round Robin by manually handling the DNS resolution and rotating through the IP addresses using the ConnectCallback property of SocketsHttpHandler.
321+
DNS Round Robin is a technique used to distribute network traffic across multiple servers by rotating through a list of IP addresses associated with a single domain name. This helps in load balancing and improving the availability of services. When using `HttpClient`, you can implement DNS Round Robin by manually handling the DNS resolution and rotating through the IP addresses using the `ConnectCallback` property of `SocketsHttpHandler`.
322322

323-
To enable DNS Round Robin with HttpClient, you can use the ConnectCallback property to manually resolve the DNS entries and rotate through the IP addresses. Here's an example for `HttpWebRequest` and `HttpClient`:
323+
To enable DNS Round Robin with `HttpClient`, you can use the `ConnectCallback` property to manually resolve the DNS entries and rotate through the IP addresses. Here's an example for `HttpWebRequest` and `HttpClient`:
324324

325325
**Old code using `HttpWebRequest`**:
326326

@@ -343,11 +343,11 @@ For the implementation of `DnsRoundRobinConnector`, see [DnsRoundRobin.cs](https
343343

344344
:::code source="../snippets/httpclient/Program.DnsRoundRobin.cs" id="DnsRoundRobinConnect":::
345345

346-
### Example: Set SocketsHttpHandler properties
346+
### Example: Set `SocketsHttpHandler` properties
347347

348-
SocketsHttpHandler is a powerful and flexible handler in .NET that provides advanced configuration options for managing HTTP connections. By setting various properties of SocketsHttpHandler, you can fine-tune the behavior of your HTTP client to meet specific requirements, such as performance optimization, security enhancements, and custom connection handling.
348+
`SocketsHttpHandler` is a powerful and flexible handler in .NET that provides advanced configuration options for managing HTTP connections. By setting various properties of `SocketsHttpHandler`, you can fine-tune the behavior of your HTTP client to meet specific requirements, such as performance optimization, security enhancements, and custom connection handling.
349349

350-
Here's an example of how to configure SocketsHttpHandler with various properties and use it with HttpClient:
350+
Here's an example of how to configure `SocketsHttpHandler` with various properties and use it with `HttpClient`:
351351

352352
```c#
353353
var cookieContainer = new CookieContainer();
@@ -374,11 +374,11 @@ using var response = await client.GetAsync(uri);
374374

375375
This functionality is specific to certain platforms and is somewhat outdated. If you need a workaround, you can refer to [this section of the code](https://github.com/dotnet/runtime/blob/171f1a73a9f0fa77464995bcb893a59b9b98bc3d/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs#L1678-L1684).
376376

377-
## Usage of Certificate and TLS-related properties in HttpClient
377+
## Usage of Certificate and TLS-related properties in `HttpClient`
378378

379379
When working with `HttpClient`, you may need to handle client certificates for various purposes, such as custom validation of server certificates or fetching the server certificate. `HttpClient` provides several properties and options to manage certificates effectively.
380380

381-
### Example: Check certificate revocation list with SocketsHttpHandler
381+
### Example: Check certificate revocation list with `SocketsHttpHandler`
382382

383383
The `CheckCertificateRevocationList` property in `SocketsHttpHandler.SslOptions` allows developers to enable or disable the check for certificate revocation lists (CRL) during SSL/TLS handshake. Enabling this property ensures that the client verifies whether the server's certificate has been revoked, enhancing the security of the connection.
384384

@@ -445,10 +445,10 @@ Mutual authentication, also known as two-way SSL or client certificate authentic
445445
To enable mutual authentication, follow these steps:
446446

447447
- Load the client certificate.
448-
- Configure the HttpClientHandler or SocketsHttpHandler to include the client certificate.
448+
- Configure the `HttpClientHandler` or `SocketsHttpHandler` to include the client certificate.
449449
- Set up the server certificate validation callback if custom validation is needed.
450450

451-
Here's an example using SocketsHttpHandler:
451+
Here's an example using `SocketsHttpHandler`:
452452

453453
```csharp
454454
var handler = new SocketsHttpHandler
@@ -478,21 +478,21 @@ Headers play a crucial role in HTTP communication, providing essential metadata
478478

479479
### Set request headers
480480

481-
Request headers are used to provide additional information to the server about the request being made. Common use cases include specifying the content type, setting authentication tokens, and adding custom headers. You can set request headers using the `DefaultRequestHeaders` property of `HttpClient` or the Headers property of `HttpRequestMessage`.
481+
Request headers are used to provide additional information to the server about the request being made. Common use cases include specifying the content type, setting authentication tokens, and adding custom headers. You can set request headers using the `DefaultRequestHeaders` property of `HttpClient` or the `Headers` property of `HttpRequestMessage`.
482482

483483
#### Example: Set custom request headers
484484

485-
**Setting Default Custom Request Headers in HttpClient**
485+
**Setting Default Custom Request Headers in `HttpClient`**
486486

487487
```csharp
488488
var client = new HttpClient();
489489
client.DefaultRequestHeaders.Add("Custom-Header", "value");
490490
```
491491

492-
**Setting Custom Request Headers in HttpRequestMessage**
492+
**Setting Custom Request Headers in `HttpRequestMessage`**
493493

494494
```csharp
495-
var request = new HttpRequestMessage(HttpMethod.Get, uri);
495+
using var request = new HttpRequestMessage(HttpMethod.Get, uri);
496496
request.Headers.Add("Custom-Header", "value");
497497
```
498498

@@ -503,7 +503,7 @@ For a comprehensive list of common properties available in <xref:System.Net.Http
503503

504504
To set common request headers in `HttpRequestMessage`, you can use the `Headers` property of the `HttpRequestMessage` object. This property provides access to the `HttpRequestHeaders` collection, where you can add or modify headers as needed.
505505

506-
**Setting Common Default Request Headers in HttpClient**
506+
**Setting Common Default Request Headers in `HttpClient`**
507507

508508
```csharp
509509
using System.Net.Http.Headers;
@@ -512,12 +512,12 @@ var client = new HttpClient();
512512
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "token");
513513
```
514514

515-
**Setting Common Request Headers in HttpRequestMessage**
515+
**Setting Common Request Headers in `HttpRequestMessage`**
516516

517517
```csharp
518518
using System.Net.Http.Headers;
519519

520-
var request = new HttpRequestMessage(HttpMethod.Get, uri);
520+
using var request = new HttpRequestMessage(HttpMethod.Get, uri);
521521
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "token");
522522
```
523523

@@ -527,7 +527,7 @@ Content headers are used to provide additional information about the body of an
527527

528528
```csharp
529529
var client = new HttpClient();
530-
var request = new HttpRequestMessage(HttpMethod.Post, uri);
530+
using var request = new HttpRequestMessage(HttpMethod.Post, uri);
531531

532532
// Create the content and set the content headers
533533
var jsonData = "{\"key\":\"value\"}";
@@ -543,7 +543,7 @@ request.Content = content;
543543
using var response = await client.SendAsync(request);
544544
```
545545

546-
### Example: Set MaximumErrorResponseLength in HttpClient
546+
### Example: Set `MaximumErrorResponseLength` in `HttpClient`
547547

548548
The `MaximumErrorResponseLength` usage allows developers to specify the maximum length of the error response content that the handler will buffer. This is useful for controlling the amount of data that is read and stored in memory when an error response is received from the server. By using this technique, you can prevent excessive memory usage and improve the performance of your application when handling large error responses.
549549

@@ -555,10 +555,10 @@ And usage example of `TruncatedReadStream`:
555555

556556
:::code source="../snippets/httpclient/Program.TruncatedReadStream.cs" id="TruncatedReadStreamUsage":::
557557

558-
### Example: Apply CachePolicy headers
558+
### Example: Apply `CachePolicy` headers
559559

560560
> [!WARNING]
561-
> `HttpClient` does not have built-in logic to cache responses. There is no workaround other than implementing all the caching yourself. Simply setting the headers will not achieve caching.
561+
> `HttpClient` doesn't have built-in logic to cache responses. There is no workaround other than implementing all the caching yourself. Simply setting the headers won't achieve caching.
562562
563563
When migrating from `HttpWebRequest` to `HttpClient`, it's important to correctly handle cache-related headers such as `pragma` and `cache-control`. These headers control how responses are cached and retrieved, ensuring that your application behaves as expected in terms of performance and data freshness.
564564

@@ -585,7 +585,7 @@ For the implementation of `AddCacheControlHeaders`, see [AddCacheControlHeaders.
585585

586586
## Usage of buffering properties
587587

588-
When migrating from HttpWebRequest to `HttpClient`, it's important to understand the differences in how these two APIs handle buffering.
588+
When migrating from `HttpWebRequest` to `HttpClient`, it's important to understand the differences in how these two APIs handle buffering.
589589

590590
**Old code using `HttpWebRequest`**:
591591

@@ -601,16 +601,16 @@ request.AllowWriteStreamBuffering = false; // Default is `true`.
601601

602602
In `HttpClient`, there are no direct equivalents to the `AllowWriteStreamBuffering` and `AllowReadStreamBuffering` properties.
603603

604-
HttpClient does not buffer request bodies on its own, instead delegating the responsibility to the `HttpContent` used. Contents like `StringContent` or `ByteArrayContent` are logically already buffered in memory, while using `StreamContent` will not incur any buffering by default. To force the content to be buffered, you may call `HttpContent.LoadIntoBufferAsync` before sending the request. Here's an example:
604+
`HttpClient` doesn't buffer request bodies on its own, instead delegating the responsibility to the `HttpContent` used. Contents like `StringContent` or `ByteArrayContent` are logically already buffered in memory, while using `StreamContent` won't incur any buffering by default. To force the content to be buffered, you may call `HttpContent.LoadIntoBufferAsync` before sending the request. Here's an example:
605605

606606
```csharp
607607
HttpClient client = new HttpClient();
608608

609-
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
609+
using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
610610
request.Content = new StreamContent(yourStream);
611611
await request.Content.LoadIntoBufferAsync();
612612

613-
HttpResponseMessage response = await client.SendAsync(request);
613+
using HttpResponseMessage response = await client.SendAsync(request);
614614
```
615615

616616
In `HttpClient` read buffering is enabled by default. To avoid it, you may specify the `HttpCompletionOption.ResponseHeadersRead` flag, or use the `GetStreamAsync` helper.

0 commit comments

Comments
 (0)