简体   繁体   中英

Unable to create Storage account on Azure ARM using Web API

I am trying to create a storage account using Web API but it is giving me the exception that method not allowed as shown below

Web Api异常

Below is my code:

    string stAccName = "TCStorageAccount" + Guid.NewGuid().ToString().Substring(0, 8);
    stAccName = stAccName.ToLower();

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        using (var stream = new MemoryStream())
        using (var writer = new StreamWriter(stream))
        {
            var payloadText = JsonConvert.SerializeObject(parameters);

writer.Write(payloadText);
            writer.Flush();
            stream.Flush();
            stream.Position = 0;

            using (var content = new StreamContent(stream))
            {
                content.Headers.Add("Content-Type", "application/json");
                content.Headers.Add("x-ms-version", "2016-12-01");
                Uri uri = new Uri(String.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Storage/storageAccounts/{2}?api-version=2016-12-01", "subid", "resource group name", stAccName));

var response = await client.PostAsync(uri, content);

                if (!response.IsSuccessStatusCode)
                {
                    throw new InvalidOperationException(response.ReasonPhrase);
                }
           }
       }
   }

I also tried with another way as discussed in this thread Unable to create Storage account on Azure C# but still unable to create a storage account.

Any help would be appreciated. Thanks

The reason you're getting this error is because Create Storage Account is a PUT request and not a POST request.

Please change the following line of code:

var response = await client.PostAsync(uri, content);

to

var response = await client.PutAsync(uri, content);

and you should not get this Method Not Allowed (405) error.

The error is remove but getting new exception now `{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1'

The exception is cause by providing wrong parameters for storage account. You could view the detail error message using following code after the response came back.

string detailError = await response.Content.ReadAsStringAsync();

Here is a sample parameters which could create a storage account successfully using your code on my side.

{
  "kind": "Storage",
  "location": "South Central US",
  "sku": {
    "name": "Standard_LRS"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM