Search code examples
c#httprequest

WPF / C# Submit button to POST API


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.


Solution

  • 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();
    }