Here's one method to do all the CRUD for REST API
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
enum Method { GET, POST, PUT, DELETE }
static HttpClient Client;
static async Task<HttpResponseMessage> MakeApiCall(Uri
baseUri, string apiPath, Method
mehtod, string token, object obj = null)
{
//
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
if (Client == null || Client.BaseAddress.AbsoluteUri !=
baseUri.AbsoluteUri)
{
Client = new HttpClient();
Client.BaseAddress = baseUri;
}
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
if (!string.IsNullOrEmpty(token))
Client.DefaultRequestHeaders.Authorization
= new
AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = null;
switch (mehtod)
{
case Method.GET:
response = await
Client.GetAsync(apiPath);
break;
case Method.POST: // create
response = await
Client.PostAsJsonAsync(apiPath, obj);
break;
case Method.PUT: // update
response = await
Client.PutAsJsonAsync(apiPath, obj);
break;
case Method.DELETE:
response = await
Client.DeleteAsync(apiPath);
break;
}
return response;
}
//---------------------------
// Usage
var response = await MakeApiCall(new Uri(baseUrl), "/api/Auth", Method.GET, token);
Console.WriteLine(await
response.Content.ReadAsStringAsync());
response = await MakeApiCall(new Uri(baseUrl), "/api/Auth", Method.PUT, token,
new { id = 2, newUser = true, onBoardingComplete
= true });
Console.WriteLine(await
response.Content.ReadAsStringAsync());
Comments
Post a Comment