Microsoft Dynamics 365 Business Central提供了一种使用Oauth2身份验证API的简单方式。本例展示了如何通过C#代码从Business Central API请求令牌:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace BusinessCentralOAuth2
{
public class OAuthHelper
{
public async Task GetAccessTokenAsync(string tenantId, string clientId, string clientSecret, string apiResource)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token");
var request = new HttpRequestMessage(HttpMethod.Post, "");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair("grant_type", "client_credentials"),
new KeyValuePair("client_id", clientId),
new KeyValuePair("client_secret", clientSecret),
new KeyValuePair("scope", $"{apiResource}/.default")
});
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject(json);
return result.access_token;
}
}
}
}
只需提供您的订阅ID、客户端ID、客户机密和API资源URI即可。
例如,要使用Business Central API请求令牌,可以使用以下代码:
var helper = new OAuthHelper();
var token = await helper.GetAccessTokenAsync("mytenantid", "myclientid", "myclientsecret", "https://api.businesscentral.dynamics.com/v2.0/mytenantid/myenvironment/odata/");
此代码将返回一个令牌字符串,其中包含对Business Central API的身份验证。
请注意,此示例使用了Newtonsoft.Json NuGet软件包,因此如果您在使用您自己的代码时遇到缺少此程序集的错误,您需要在您的项目中安装此软件包。
上一篇:BusinessCentral页面中的Blob字段无法显示。
下一篇:BusinessDynamics365API-NotabletogetWeb/ecommerceenableditemsonly