1

I am still very new to programming in .net. I am trying to write a simple console app to test some endpoints in our scheduling software. They provide the following on how to authenticate to receive a JWT token for the next step in authentication.

POST /platform/api/v1/clientauthentication HTTP/1.1
Content-Type: application/json

{ "clientID": "", "secret": "" }

This returns a JWT which in turn requires me to authenticate as a user to access some of the endpoints

POST /platform/api/v1/authentication/token HTTP/1.1
Content-Type: application/json

X-applicationname-api-token: (client token goes in this header)

{ "username": "test", "password": "test" }

I'm trying to use System.Net.Http, but once I create the client and set the base address I am lost on how to set the headers. I've searched and can't find anything other than heavily convoluted examples. I come from Python and it is so much easier to do. I just can't get my head around this in C#.

Thank you for any responses.

Edit: I figured out a way to do this, but it just seems...wrong:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(API_URL);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var headers = new Dictionary<string, string>();
    headers.Add("clientID", CLIENT_ID);
    headers.Add("secret", API_SECRET);

    var response = client.PostAsJsonAsync("clientauthentication", headers).Result.Content.ReadAsStringAsync().Result;

    var json = JObject.Parse(response);
}

I'm sure there is a better way. The more code I try to write, the more I learn I hardly know anything. A bit of a bummer.

Derrick D
  • 21
  • 1
  • 3
  • Could you pls use asp.net core web application instead of console app? If you can, then you may follow this document to [send http request](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0). By the way, in your description, it seems that you need to send a request to get the token first and then call api with the token in the request header. About adding request header, you may follow [this answer](https://stackoverflow.com/a/54695555). – Tiny Wang Jul 04 '22 at 06:41

0 Answers0