根据您提到的异常,我假设您没有为应用程序分配正确的权限,更多细节我们可以参考将应用程序分配给角色。
我还创建了一个演示,它在我这边可以正常工作。以下是我的演示代码。
static string appId = "application name";
static string secretKey = "scretkey";
static string tenantId = "tenant id";
private static readonly string _subscriptionId = "subscription Id";
static void Main(string[] args)
{
var resourceGroupName = "resource Group name";
var accountName = "batch account name";
var location = "eastus2";// location
var accessToken = GetAccessToken(tenantId, appId, secretKey).Result;
BatchManagementClient batchManagementClient =
new BatchManagementClient(new TokenCredentials(accessToken)) {SubscriptionId = _subscriptionId};
var batchAccount = batchManagementClient.BatchAccount.Create(resourceGroupName, accountName, new BatchAccountCreateParameters() { Location = location });
}
public static async Task<string> GetAccessToken(string azureTenantId, string azureAppId, string azureSecretKey)
{
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(appId, secretKey);
var tokenResponse = await context.AcquireTokenAsync("https://management.azure.com/", clientCredential);
var accessToken = tokenResponse.AccessToken;
return accessToken;
}
包.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Azure.Management.Batch" version="3.0.0" targetFramework="net461" />
<package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.28.3" targetFramework="net461" />
<package id="Microsoft.Rest.ClientRuntime" version="2.3.8" targetFramework="net461" />
<package id="Microsoft.Rest.ClientRuntime.Azure" version="3.3.8" targetFramework="net461" />
<package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.3.0" targetFramework="net461" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net461" />
</packages>