GetAsync azure调用没有结果

时间:2017-03-22 09:34:51

标签: c# azure asynchronous

使用VS 2017社区。天青。

我有Azure设置,我有一个空白的webapp,仅用于测试目的。

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

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

警告:代码都是Sausage代码/原型。

控制器

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

    }
}

ISSUE: 好的,我遇到的问题是我的代码中的异步死锁。所以我查看了这个帖子stack post here

我通过在大多数await声明中放入.ConfigureAwait(false)来修复问题。

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

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

代码看起来很好并且运行正常,任何可以帮助验证的人都会很好,但可以假设这没关系。 问题是在azure中配置,当您注册应用程序时,您必须通过订阅设置一定数量的Access控件。

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

可能不需要一半&#34; IAM&#34;添加到注册的应用程序的订阅,我只是添加相关的和每次调试,直到最终我得到预期的结果。