c# - GetAsync azure 调用没有结果

标签 c# azure asynchronous

使用 VS 2017 社区。 azure 。

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

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

以下代码应该...联系azure提供 key (该站点在azure Active Directory中注册)。 从这里我得到一个 token ,然后我可以用它来联系 azure api 并获取站点列表。

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

Controller

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获取 token ...

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) 解决了这些问题。

代码运行并使用 token 等一路返回到 Controller ,并通过 MakeARMRequests(HttpClient client) 方法运行,但是当我调试时,json 仅返回 1 个结果“{[]}”,因此忽略循环。

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

最佳答案

不确定这是否是您现在面临的问题,但您从不等待代码中第一个方法 Index 中异步操作的结果。 MainAsync().ConfigureAwait(false); 将立即返回并继续下一个 block ,同时任务 MainAsync() 将在后台启动。 catch 处理程序也不执行任何操作,因为您不等待结果。

选项 1(推荐)

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

    return View();
}

如果由于某种原因无法使用async/await,请选择选项 2

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

    return View();
}

关于c# - GetAsync azure 调用没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42947585/

相关文章:

c# - 等待流的人口

c# - 如何从必须留在主线程上的方法统一调用异步方法

c# - 忽略模型更改后 Razor ASP.NET

c# - 如何使用 AngleSharp 查找和替换链接上的 href 值?

Azure 数据湖存储 - 将 JSON 转换为 CSV

Azure CosmosDB 触发器根据另一个集合中的值更新集合

Azure DevOps Pipeline - 构建 Docker 镜像并将其推送到具有受限网络访问权限的 Azure 容器注册表

c# - 如何将文件编码从 windows-1251 更改为 utf-8

c# - Nest 5.6 - 如何插入已存在 id 的文档?

javascript - TS2488 : Type 'string | null' must have a '[Symbol.iterator]()' method that returns an iterator