Home > Net >  C# Microsoft Graph Api Request_BadRequest
C# Microsoft Graph Api Request_BadRequest

Time:01-18

Every time I try to add a license to a user using the Microsoft Graph Api in C#, I get this error:

Microsoft.Graph.ServiceException: 'Code: Request_BadRequest Message: License assignment cannot be done for user with invalid usage location.

My code is here


using Azure.Identity;
using Microsoft.Graph;

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenantid";
var clientId = "clientid";
var clientSecret = "clientsecret";

var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

var user = new User
{
    AccountEnabled = true,
    DisplayName = "test",
    MailNickname = "test",
    UserPrincipalName = "[email protected]",
    PasswordProfile = new PasswordProfile
    {
        ForceChangePasswordNextSignIn = true,
        Password = "random.1234"
    }
};

var addLicenses = new List<AssignedLicense>()
{
    new AssignedLicense
    {
        SkuId = Guid.Parse("314c4481-f395-4525-be8b-2ec4bb1e9d91")
    }
};
var removeLicenses = Array.Empty<Guid>();

await graphClient.Users
    .Request()
    .AddAsync(user);
Console.WriteLine("Kullanıcı Açıldı");

await graphClient.Users["[email protected]"]
    .AssignLicense(addLicenses, removeLicenses)
    .Request()
    .PostAsync();
Console.WriteLine("Lisans Eklendi");

CodePudding user response:

When you create a new user you need to set UsageLocation.

Documentation says that usageLocation is required for users that will be assigned licenses due to legal requirement to check for availability of services in countries.

var user = new User
{
    AccountEnabled = true,
    DisplayName = "test",
    MailNickname = "test",
    UserPrincipalName = "[email protected]",
    PasswordProfile = new PasswordProfile
    {
        ForceChangePasswordNextSignIn = true,
        Password = "random.1234"
    },
    UsageLocation = "TR" // for Turkey
};

// rest of the code without changes
var addLicenses = new List<AssignedLicense>()
{
    new AssignedLicense
    {
        SkuId = Guid.Parse("314c4481-f395-4525-be8b-2ec4bb1e9d91")
    }
};
var removeLicenses = Array.Empty<Guid>();

await graphClient.Users
    .Request()
    .AddAsync(user);
Console.WriteLine("Kullanıcı Açıldı");

await graphClient.Users["[email protected]"]
    .AssignLicense(addLicenses, removeLicenses)
    .Request()
    .PostAsync();
Console.WriteLine("Lisans Eklendi");
  • Related