PROWAREtech
ASP.NET Core: How to Issue a GET Request from an Endpoint using C#
Using C#, GET JSON from a REST API endpoint; how to receive JSON data from a REST API.
This article requires ASP.NET Core, and is compatible with .NET Core 3.1, .NET 6 and .NET 8.
To POST data to an endpoint, see this article.
It is very easy to post GET data from an endpoint using HttpClient
. WebClient
and HttpWebRequest
should not be used as they are deprecated as of the writing of this article.
GET JSON from Endpoint
private async Task GetJson()
{
string json = System.Text.Json.JsonSerializer.Serialize(new { name = "test" });
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
var response = await client.GetAsync("http://0.0.0.0/endpoint");
var repsonseObject = System.Text.Json.JsonSerializer.Deserialize<object> // NOTE: replace "object" with class name
(await response.Content.ReadAsStringAsync());
// NOTE: use responseObject here
}
}
await GetJson();
GET with JSON Web Token Bearer Authentication
It is simple to GET from an endpoint using JWT Bearer Authentication. Simply use the HttpRequestMessage
class and the SendAsync()
method.
private async Task GetJsonWithJwtAuth()
{
object? responseObject = null; // NOTE: replace "object" with the class name
string json = System.Text.Json.JsonSerializer.Serialize(new { data = "ABCD1234" });
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
var requestMsg = new HttpRequestMessage(HttpMethod.Get, "http://0.0.0.0/endpoint");
string jwt = "asidlfbvc87w4tguiwebo87w4gqowuy4bfoq4837yo8f3fl"; // NOTE: THIS IS THE JSON WEB TOKEN; REPLACE WITH A REAL JWT
requestMsg.Headers.Add("Authorization", "Bearer " + jwt);
var response = await client.SendAsync(requestMsg);
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// NOTE: THEN TOKEN HAS EXPIRED; HANDLE THIS SITUATION
}
else if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
responseObject = null;
else if (response.IsSuccessStatusCode)
responseObject = await response.Content.ReadFromJsonAsync<object>(); // NOTE: replace "object" with the class name
}
}
await GetJsonWithJwtAuth();
Comment