1.8 API Usage from .NET Application by HttpClient

To get access token from .net application you can use following example. After getting access token, you can use the token on your requests.
Note: You can also use, Webclient and Restclient (easy) if you prefer.

string clientId = “yourclientId”;
string clientSecret = “yourClientSecret”;
string baseUrl = “http://your server base url for example: http://myxiboserver.com”;

private static async Task<string> GetAccessToken()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);
                // We want the response to be JSON.
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                // You must provide one Authorization method. No need any value, but must have a method. Othervise you will get 404 page not found error.
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic");
                // Build up the data to POST.
                List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
                postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                postData.Add(new KeyValuePair<string, string>("client_id", clientId));
                postData.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                FormUrlEncodedContent content = new FormUrlEncodedContent(postData);

                // Post to the Server and parse the response.
                HttpResponseMessage response = await client.PostAsync("/api/authorize/access_token", content);
                string jsonString = await response.Content.ReadAsStringAsync();
                object responseData = JsonConvert.DeserializeObject(jsonString);

                // return the Access Token.
                return ((dynamic)responseData).access_token;
            }
        }
1 Like