如何在创建新的azure订阅后设置贡献者角色?

时间:2016-07-12 07:20:21

标签: c# rest azure

我使用带有以下代码的microsoft CREST API创建了一个新订阅:

WebClient client = new WebClient();
SATokenFormatReseller SA_Token = GetSAResellerToken();
client.Headers[HttpRequestHeader.Accept] = "application/json";
client.Headers[HttpRequestHeader.Authorization] = "Bearer " + SA_Token.access_token;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add("api-version", ApiVersion);
client.Headers.Add("x-ms-correlation-id", Guid.NewGuid().ToString());
client.Headers.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
var reqOrderObj = CreateReqOrderObject(service, mpn);
var reqOrderJson = JsonConvert.SerializeObject(reqOrderObj, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
string res = client.UploadString("https://api.cp.microsoft.com/" + TenantId + "/orders", "POST", reqOrderJson);

创建成功订阅后,我尝试使用管理azure核心api为新订阅设置贡献者角色,这样:

public bool CreateRoleAssignment(string subscriptionId, string tenantId, string principalId)
{
    bool roleGranted = false;
    var azureToken = GetAzureAuthTokenForCustomerTenant(NativeClientId, PartnerCenterUser, PartnerCenterPassword, tenantId);
    string responseContent = String.Empty;
    var roleAssignmentId = Guid.NewGuid().ToString(); 
    var correlationId = Guid.NewGuid().ToString();
    var request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Authorization/roleAssignments/{1}?api-version=2015-07-01", subscriptionId, roleAssignmentId));

    request.Method = "PUT";
    request.Accept = "application/json";
    request.ContentType = "application/json";

    request.Headers.Add("x-ms-correlation-id", correlationId);
    request.Headers.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
    request.Headers.Add("Authorization", "Bearer " + azureToken.AccessToken);

    string content = Json.Encode(CreateRoleAssignmentRequestData(subscriptionId, principalId));

    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(content);
    }

    try
    {
        var response = request.GetResponse();
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            responseContent = reader.ReadToEnd();
            roleGranted = true;
        }
    }
    catch (WebException webException)
    {
        using (var reader = new StreamReader(webException.Response.GetResponseStream()))
        {
            responseContent = reader.ReadToEnd();
            roleGranted = false;
        }
    }

    return roleGranted;
}

但响应是订阅不存在。

一段时间后,如果我运行相同的代码(CreateRoleAssignment),则该角色将成功发送给订阅。

创建订阅后,我怎么能实现这个过程?

1 个答案:

答案 0 :(得分:1)

正如@GauravMantri所说,使用异步轮询作为下面的示例代码。

var azureToken = GetAzureAuthTokenForCustomerTenant(NativeClientId, PartnerCenterUser, PartnerCenterPassword, tenantId);
string responseContent = String.Empty;
var roleAssignmentId = Guid.NewGuid().ToString(); 
var correlationId = Guid.NewGuid().ToString();
string url = string.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Authorization/roleAssignments/{1}?api-version=2015-07-01", subscriptionId, roleAssignmentId);
string content = Json.Encode(CreateRoleAssignmentRequestData(subscriptionId, principalId));

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Add("Accept", "application/json");
    client.DefaultRequestHeaders.Add("Content-Type", "application/json");
    client.DefaultRequestHeaders.Add("x-ms-correlation-id", correlationId);
    client.DefaultRequestHeaders.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + azureToken.AccessToken);
    var response = await client.PutAsync(url, content);
    while(!response.IsSuccessStatusCode) 
    {
        response = await client.PutAsync(url, content);
    }
    Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}