400-BadRequest while call rest api of azure Web App

岁酱吖の 提交于 2019-12-12 03:27:43

问题


 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);

This is how I make a call to Azure WebApp rest api but I am getting statuscode : BadRequest


回答1:


There are some issues with your code:

  • You're mixing Azure Service Management API with Azure Resource Manager (ARM) API. API to stop a web app is a Resource Manager API thus you don't need to provide x-ms-version.
  • You're missing the Authorization header in your request. ARM API requests require an authorization header. Please see this link on how to perform ARM API requests: https://docs.microsoft.com/en-us/rest/api/gettingstarted/.

Based on these, I modified your code:

    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);
    }

Please try using this code. Assuming you have acquired proper token, the code should work.



来源:https://stackoverflow.com/questions/41716480/400-badrequest-while-call-rest-api-of-azure-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!