在azure Web App的呼叫休息api时进行400-BadRequest

时间:2017-01-18 10:07:25

标签: azure azure-app-service-envrmnt

 var client = new HttpClient();
 client.DefaultRequestHeaders.Add("x-ms-version", "2016-05-31");
 var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]
 {
    new KeyValuePair<string, string>("api-version", "2016-08-01")
 });
 content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
 var response = client.PostAsync("https://management.azure.com/subscriptions/SuscriptionID/resourceGroups/Default-Web-SoutheastAsia/providers/Microsoft.Web/sites/MyAppName/stop?", content);

这是我调用Azure WebApp rest api的方法,但我收到了statuscode:BadRequest

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:

  • 您正在将Azure Service Management APIAzure Resource Manager (ARM) API混合。用于停止Web应用程序的API是资源管理器API,因此您无需提供x-ms-version
  • 您的请求中缺少Authorization标头。 ARM API请求需要授权标头。请参阅此链接,了解如何执行ARM API请求:https://docs.microsoft.com/en-us/rest/api/gettingstarted/

基于这些,我修改了你的代码:

    static async void StopWebApp()
    {
        var subscriptionId = "<your subscription id>";
        var resourceGroupName = "<your resource group name>";
        var webAppName = "<your web app name>";
        var token = "<bearer token>";
        var url = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/stop?api-version=2016-08-01", subscriptionId, resourceGroupName, webAppName);
        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
        var t = await client.PostAsync(url, null);
        var response = t.StatusCode;
        Console.WriteLine(t.StatusCode);
    }

请尝试使用此代码。假设您已获得正确的令牌,则代码应该可以正常工作。