【问题标题】:GetAsync azure call no resultGetAsync 天蓝色调用没有结果
【发布时间】:2017-08-14 07:51:31
【问题描述】:

使用 VS 2017 社区。天蓝色。

我有 Azure 设置,我创建了一个空白 web 应用程序,仅用于测试目的。

我的实际站点是 Angular2 MVC5 站点,目前在本地运行。

以下是应... 联系 azure 提供密钥(该站点已在 azure Active Directory 中注册)。 从这里我得到一个令牌,然后我可以用来联系 azure api 并获取站点列表。

警告:代码都是香肠代码/原型。

控制器

public ActionResult Index()
{
    try
        {
            MainAsync().ConfigureAwait(false);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.GetBaseException().Message);
        }

        return View();
}

static async System.Threading.Tasks.Task MainAsync()
    {
        string tenantId = ConfigurationManager.AppSettings["AzureTenantId"];
        string clientId = ConfigurationManager.AppSettings["AzureClientId"];
        string clientSecret = ConfigurationManager.AppSettings["AzureClientSecret"];

        string token = await AuthenticationHelpers.AcquireTokenBySPN(tenantId, clientId, clientSecret).ConfigureAwait(false);

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.BaseAddress = new Uri("https://management.azure.com/");

            await MakeARMRequests(client);
        }
    }

static async System.Threading.Tasks.Task MakeARMRequests(HttpClient client)
    {
        const string ResourceGroup = "ProtoTSresGrp1";

        // Create the resource group

        // List the Web Apps and their host names

        using (var response = await client.GetAsync(
            $"/subscriptions/{Subscription}/resourceGroups/{ResourceGroup}/providers/Microsoft.Web/sites?api-version=2015-08-01"))
        {
            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
            foreach (var app in json.value)
            {
                Console.WriteLine(app.name);
                foreach (var hostname in app.properties.enabledHostNames)
                {
                    Console.WriteLine("  " + hostname);
                }
            }
        }
    }

Controller 类使用从 Azure 获取令牌的 静态帮助程序类...

public static class AuthenticationHelpers
{
    const string ARMResource = "https://management.core.windows.net/";
    const string TokenEndpoint = "https://login.windows.net/{0}/oauth2/token";
    const string SPNPayload = "resource={0}&client_id={1}&grant_type=client_credentials&client_secret={2}";

    public static async Task<string> AcquireTokenBySPN(string tenantId, string clientId, string clientSecret)
    {
        var payload = String.Format(SPNPayload,
                                    WebUtility.UrlEncode(ARMResource),
                                    WebUtility.UrlEncode(clientId),
                                    WebUtility.UrlEncode(clientSecret));

        var body = await HttpPost(tenantId, payload).ConfigureAwait(false);
        return body.access_token;
    }

    static async Task<dynamic> HttpPost(string tenantId, string payload)
    {
        using (var client = new HttpClient())
        {
            var address = String.Format(TokenEndpoint, tenantId);
            var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
            using (var response = await client.PostAsync(address, content).ConfigureAwait(false))
            {
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Status:  {0}", response.StatusCode);
                    Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync());
                }

                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
            }
        }

    }
}

问题: 好的,所以我面临的问题是我的代码中的异步死锁。所以我看了这个堆栈帖子stack post here

我通过在大多数等待声明中添加 .ConfigureAwait(false) 来解决问题。

代码运行并使用令牌等一直返回到控制器,并通过 MakeARMRequests(HttpClient 客户端) 方法运行,但是当我调试时 json 仅返回 1 个结果“{[]}”,因此忽略循环。

我的问题是,我的代码是这里的罪魁祸首吗?或者这会指向 azure 中的配置设置吗?

【问题讨论】:

  • however the json only returns 1 result "{[]}" when i debug...

标签: c# azure asynchronous


【解决方案1】:

不确定这是否是您现在面临的问题,但您永远不会在代码中的第一种方法 Index 中等待异步操作的结果。 MainAsync().ConfigureAwait(false); 将立即返回并继续下一个块,而任务 MainAsync() 将在后台启动。 catch 处理程序也不做任何事情,因为您不等待 f 或结果。

选项 1(推荐)

public async Task<ActionResult> Index()
{
    try
    {
        await MainAsync().ConfigureAwait(false);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.GetBaseException().Message);
    }

    return View();
}

选项 2 如果您由于某种原因不能使用async/await

public ActionResult Index()
{
    try
    {
        MainAsync().GetAwaiter().GetResult();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.GetBaseException().Message);
    }

    return View();
}

【讨论】:

  • 感谢您了解这一点,虽然不是答案,但它是未来可能被忽视的问题。赞成
【解决方案2】:

代码看起来不错并且运行良好,任何可以帮助验证的人都会很好,但可以假设这没问题。 问题是 azure 中的配置,当您注册应用时,您必须通过订阅设置一定数量的访问控制。

在这种情况下,我为 web api 设置了一些更具体的东西,现在将应用程序设置为所有者并参考服务管理 api。

可能不需要在注册应用程序的订阅中添加一半的“IAM”,我只是简单地添加了相关的并每次调试,直到最终得到预期的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2020-11-26
    • 2017-05-01
    相关资源
    最近更新 更多