Business Centralへデータ編集やデータ取得を行うAPIにOAuth2.0を用いてtokenや認証を行う。
AzureのApp Registryの設定や、Business Centralの認証の設定は、こちらに詳しく記載があるので、こちでは、C#側でHttpClientを使用したBusiness Central API実行ロジックを紹介する。
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
string url = "https://login.microsoftonline.com/<テナントID>/oauth2/v2.0/token";
string accessToken = string.Empty;
Uri uri = new Uri(url);
Dictionary<string, string> requestBody = new Dictionary<string, string>
{
{"grant_type", "client_credentials" },
{"client_id" , "AzureからApplication IDを取得" },
{"client_secret", "AzureからSecret Valueを取得" },
{"scope", "https://api.businesscentral.dynamics.com/.default" }
};
FormUrlEncodedContent request = new FormUrlEncodedContent(requestBody);
try
{
HttpResponseMessage response = await client.PostAsync(uri, request);
string content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
JsonDocument document = JsonDocument.Parse(content);
accessToken = document.RootElement.GetProperty("access_token").GetString();
}
else
{
}
}
catch (Exception ex)
{
}
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await client.PostAsync("Business CentralのAPI URL", new StringContent(JsonConvert.SerializeObject("request用のJSON"),Encoding.UTF8, "application/json"));
var resString = await response.Content.ReadAsStringAsync();