Represents a Keep-Alive header value.
The Keep-Alive header is used by clients and servers to indicate how to handle persistent HTTP connections. This class provides a strongly-typed representation for parsing and constructing this header value.
| Name | Type | Description |
|---|---|---|
Connections |
System.Collections.Generic.IEnumerable<System.Net.Http.Headers.NameValueHeaderValue> |
Gets a collection of NameValueHeaderValue objects that represent the parameters of the Keep-Alive header. |
Identifier |
string |
Gets or sets a unique identifier for the Keep-Alive header. This property is not commonly used. |
Timeout |
System.Nullable<System.TimeSpan> |
Gets or sets the timeout value for a Keep-Alive connection. |
| Signature | Description |
|---|---|
KeepAliveHeaderValue() |
Initializes a new instance of the KeepAliveHeaderValue class. |
| Name | Parameters | Returns | Description |
|---|---|---|---|
Parse(string input) |
string input |
KeepAliveHeaderValue |
Parses a Keep-Alive header value from a string. |
TryParse(string input, out KeepAliveHeaderValue value) |
string inputout KeepAliveHeaderValue value
|
bool |
Tries to parse a Keep-Alive header value from a string. Returns true if successful, false otherwise. |
ToString() |
None | string |
Returns the string representation of the Keep-Alive header value. |
Here's how you might use KeepAliveHeaderValue to manage Keep-Alive headers in your HTTP requests:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
public class KeepAliveExample
{
public static void Main(string[] args)
{
// Create a default Keep-Alive header
KeepAliveHeaderValue keepAlive = new KeepAliveHeaderValue();
Console.WriteLine($"Default Keep-Alive: {keepAlive}"); // Example: ""
// Set custom parameters for Keep-Alive
keepAlive.Timeout = TimeSpan.FromSeconds(60);
keepAlive.Connections.Add(new NameValueHeaderValue("timeout", "60"));
keepAlive.Connections.Add(new NameValueHeaderValue("max", "10"));
Console.WriteLine($"Custom Keep-Alive: {keepAlive}"); // Example: "timeout=60, max=10, timeout=60s"
// Using HttpClient with Keep-Alive
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com");
request.Headers.ConnectionClose = false; // Explicitly indicate keep-alive is desired (though often default)
request.Headers.TryAddWithoutValidation("Keep-Alive", keepAlive.ToString());
Console.WriteLine($"Request Headers: {request.Headers}");
// You would then send the request:
// HttpResponseMessage response = await client.SendAsync(request);
}
// Parsing an existing Keep-Alive header
string headerString = "timeout=30, max=5";
if (KeepAliveHeaderValue.TryParse(headerString, out KeepAliveHeaderValue parsedKeepAlive))
{
Console.WriteLine($"Parsed Timeout: {parsedKeepAlive.Timeout}");
foreach (var param in parsedKeepAlive.Connections)
{
Console.WriteLine($"Parsed Parameter: {param.Name}={param.Value}");
}
}
}
}