调用Azure App Service应用设置POST接口失败,代码排查求助
调用Azure App Service应用设置API失败的解决方法
我需要通过Azure App Service获取应用的应用设置,参考微软官方的List Application Settings REST API文档后,在官网的「Try-it」功能中传入正确参数能调用成功,但在VS项目中编写的代码却无法正常运行。
我编写了如下HttpClient代码用于调用该接口,但未能成功:
string clientId = "aaa"; string clientSecret = "bbb"; string tenantId = "ccc"; var subscriptionId = "ddd"; var resourceGroupName = "eee"; var name = "fff"; string apiUrl = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/appsettings/list?api-version=2022-03-01"; try { IConfidentialClientApplication app = ConfidentialClientApplicationBuilder .Create(clientId) .WithClientSecret(clientSecret) .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}")) .Build(); var scopes = new string[] { "https://management.azure.com/.default" }; var result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = new StringContent(String.Empty, Encoding.UTF8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync(apiUrl, content); if (response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine("API Response:"); Console.WriteLine(responseContent); } else { Console.WriteLine($"API call failed with status code: {response.StatusCode}"); } } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); }
我猜测问题可能出在PostAsync方法上。另外,我之前调用GET请求(如Get Function接口)是正常的。
已解决:为Azure AD注册的应用在函数应用中添加「Website Contributor」角色后,问题得到解决。
内容的提问来源于stack exchange,提问作者CoenJ
相关产品推荐
相关产品推荐

