返回

使用 Azure 函数 C# 返回资源组对象和 List<string>

发布时间:2022-08-18 05:36:23 263
# flask

我正在创建一个 API,我可以在其中检索给定订阅中的资源组列表或检索资源组 ID,但我无法同时返回两者

 [Function("getRg")]
        public async Task GetRgs([HttpTrigger(AuthorizationLevel.Function, "get", Route = "rg")] HttpRequestData req,
            string? rg,
            string sub,
            FunctionContext functionContext)
        {

            ArmClient client = new ArmClient(new DefaultAzureCredential());
            SubscriptionCollection subscriptions = client.GetSubscriptions();
            SubscriptionResource subscription = await subscriptions.GetAsync(sub);

            ResourceGroupCollection resourceGroups = subscription.GetResourceGroups();


            if (!string.IsNullOrEmpty(rg))
            {
                string resJson = "";
                ResourceGroupResource resourceGroup = await resourceGroups.GetAsync(rg);
                resourceGroup = await resourceGroup.GetAsync();
                resJson = JsonSerializer.Serialize(resourceGroup.Data.Id);


                _logger.LogInformation($"requested RG: ${resJson}");
                var response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
                response.WriteString(resJson);
                return response;
            }
            else 
            {
                var rgList = new List();

                foreach (var rgItem in resourceGroups)
                {

                    rgList.Add(rgItem.Data.Name);

                }

                _logger.LogInformation($"rg list: {rgList}");
                var response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "text/html, charset=utf-8");
                await response.WriteAsJsonAsync(rgList);

                return response;
            }

        }

当我试图通过不提供rg name参数来获取列表时,出现以下错误:

System.Private.CoreLib: Exception while executing function: Functions.getRg. System.Private.CoreLib: Result: Failure
Exception: System.AggregateException: One or more errors occurred. (The format of value 'text/plain, charset=utf-8' is invalid.)

在这种情况下,响应标头中的格式应该是什么?我做得对吗?

我不理解的第二个行为是,当我试图使用此行获取一个rg的id时:

resJson = JsonSerializer.Serialize(resourceGroup.Data.Id);

我只希望得到id,但是我得到了一个不同的大对象。

谢谢你的帮助!

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像