C# HTTP Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
To encode HTML special characters in C#, you can use the System.Net.WebUtility.HtmlEncode()
method. This method takes a string input and returns a string where all HTML special characters are encoded. Here's an example:
string originalString = "<h1>Hello, world!</h1>"; string encodedString = System.Net.WebUtility.HtmlEncode(originalString); Console.WriteLine(encodedString);
Output:
<h1>Hello, world!</h1>
To decode HTML special characters in C#, you can use the System.Net.WebUtility.HtmlDecode()
method. This method takes a string input and returns a string where all encoded HTML special characters are decoded. Here's an example:
string encodedString = "<h1>Hello, world!</h1>"; string decodedString = System.Net.WebUtility.HtmlDecode(encodedString); Console.WriteLine(decodedString);
Output:
<h1>Hello, world!</h1>
HttpRequestMessage class C#:
HttpRequestMessage
class for constructing HTTP requests.var request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com");
HttpResponseMessage class C#:
HttpResponseMessage
class representing an HTTP response.var response = new HttpResponseMessage(HttpStatusCode.OK);
Working with HTTP headers in C#:
request.Headers.Add("User-Agent", "MyApp");
HTTP content types in C#:
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
C# HTTP request parameters:
var parameters = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; var queryString = new FormUrlEncodedContent(parameters);
HTTP status codes in C#:
response.StatusCode = HttpStatusCode.NotFound;
Handling cookies in C# HTTP requests:
var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer }) using (var client = new HttpClient(handler)) { // Make requests }
C# HTTP response headers:
var contentType = response.Content.Headers.ContentType;
C# HTTP request methods:
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.example.com");
HTTP request encoding in C#:
request.Content.Headers.ContentEncoding.Add("gzip");
C# HTTP response stream handling:
using (var stream = await response.Content.ReadAsStreamAsync()) { // Process the stream }