use endpoints in csharp

In C#, endpoints are used to access data or interact with a web service using HTTP. Endpoints can be defined as URLs that clients use to connect to a specific web service or API. Here's an example of how to use endpoints in C#:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    private const string BASE_URL = "https://jsonplaceholder.typicode.com/";

    public static async Task Main(string[] args)
    {
        using var client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        
        // Get a list of all users
        HttpResponseMessage response = await client.GetAsync("users");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
        
        // Get a specific user by id
        HttpResponseMessage response2 = await client.GetAsync("users/1");
        response2.EnsureSuccessStatusCode();
        string responseBody2 = await response2.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody2);
        
        // Post a new user to the service
        var newUser = new { name = "John Doe", username = "johndoe", email = "johndoe@example.com" };
        HttpResponseMessage response3 = await client.PostAsJsonAsync("users", newUser);
        response3.EnsureSuccessStatusCode();
        string responseBody3 = await response3.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody3);
    }
}
1286 chars
34 lines

In this example, we are using the HttpClient class to make HTTP requests to the JSONPlaceholder API. We define the base URL of the API and use different HTTP verbs (GetAsync, PostAsJsonAsync) to interact with different endpoints. We also ensure that the HTTP responses are successful and read the response content using ReadAsStringAsync.

gistlibby LogSnag