Asp.Net Core - Making API calls from backend

Viewed 380

I have an application which is calling API's from a backend cs class, using IHostedService. With basic API calls ("http://httpbin.org/ip") it is working fine and returning the correct value, however I now need to call a Siemens API which requires me to set an Authorization header, and place "grant_type=client_credentials" in the body.

 public async Task<string> GetResult()
    {
        string data = "";
        string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});

            using (HttpResponseMessage res = await client.GetAsync(baseUrl))
            {

                using (HttpContent content = res.Content)
                {

                    data = await content.ReadAsStringAsync();
                }
            }
        }

I think I have the header set up correctly but I won't know for sure until the full request gets formatted. Is it even possible to set the the body of the request to "grant_type=client_credentials"?

1 Answers

As far as I can see from Siemens API documentation they expect Form data, so it should be like:

public async Task<string> GetResult()
{
    string data = "";
    string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";

    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});

        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "client_credentials")
        });

        using (HttpResponseMessage res = await client.PostAsync(baseUrl, formContent))
        {

            using (HttpContent content = res.Content)
            {    
                data = await content.ReadAsStringAsync();
            }
        }
    }
}
Related