0

Im trying to POST the following API using C# when a user presses a button on a form. However no idea where to start. Can anyone help ?

Button Code

private void Okta_Click(object sender, RoutedEventArgs e)

{ }

POST : https://test.okta.com/api/v1/authn

Body

{
    "username": "user",
    "password": "password",
    "options": {
        "multiOptionalFactorEnroll": true,
        "warnBeforePasswordExpired": true
    }
}

When the user presses the button, it should add the user to the application.

Peter Torr - MSFT
  • 11,824
  • 3
  • 18
  • 51
Foadi
  • 11
  • 3
  • Does this answer your question? [Send HTTP POST request in .NET](https://stackoverflow.com/questions/4015324/send-http-post-request-in-net) – Alp Nov 14 '22 at 14:14
  • I'm afraid not, its not clear and I tried the first option . And was getting errors such as not able to use await – Foadi Nov 14 '22 at 18:38

1 Answers1

0

You can use the HttpClient class to make the request.

private async void Okta_Click(object sender, RoutedEventArgs e)
{
    var client = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Post, "https://test.okta.com/api/v1/authn");
    request.Content = new StringContent("{\"username\": \"user\",\"password\": \"password\",\"options\": {\"multiOptionalFactorEnroll\": true,\"warnBeforePasswordExpired\": true}}", Encoding.UTF8, "application/json");
    var response = await client.SendAsync(request);
    var responseContent = await response.Content.ReadAsStringAsync();
}
Fastnlight
  • 922
  • 2
  • 5
  • 16
  • Thank you @Fastnlight that worked. Next stage, I have the username and password in variables in earlier code, how can i use those variables in the body to replace the text strings ? – Foadi Nov 15 '22 at 10:34
  • in the string content, you do `{\”username\”: \”” + username(variable name here) “\”, \”password\”: \””password(variable name here)”\” … etc`. Or, you could use `String.Format`: `String.Format("{{\"username\": \"{0}\",\"password\": \"{1}\",\"options\": {{\"multiOptionalFactorEnroll\": true,\"warnBeforePasswordExpired\": true}}}}", username, password), Encoding.UTF8, "application/json");` – Fastnlight Nov 15 '22 at 15:13