GetAsync天蓝色呼叫没有结果 [英] GetAsync azure call no result

查看:41
本文介绍了GetAsync天蓝色呼叫没有结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用VS 2017社区.Azure.

Using VS 2017 Community. Azure.

我有Azure设置,我创建了一个空白Web应用程序只是为了测试.

I have Azure setup, I have a blank webapp created just for test purpose.

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

My actual site is an Angular2 MVC5 site, currently run locally.

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

The following is the code that should... Contact azure providing secret key(the site is registered in azure Active directory). From this i get a token i then can use to contact azure api and get list of sites.

警告:代码是所有香肠代码/原型.

WARNING: code is all Sausage code/prototype.

控制器

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获取令牌.

Controller class uses a static helper class that gets the token from 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: Ok so the issue I was faced with was Async Deadlocks in my code. So i looked at this stack post stack post here

我通过在大多数等待声明中放入.ConfigureAwait(false)来解决此问题.

I fixed the issues by putting in .ConfigureAwait(false) on most of the await declarations.

代码运行并通过令牌等方式返回到控制器,并通过MakeARMRequests(HttpClient client)方法运行,但是json在我调试时仅返回1结果"{[]}",因此忽略了循环.

Code runs and gets all the way back to the controller with a token etc and runs through the MakeARMRequests(HttpClient client) method, however the json only returns 1 result "{[]}" when i debug and as such ignores the loops.

我的问题是,我的代码是这里的罪魁祸首吗?还是会指向天蓝色的配置设置?

My question is, is my code the culprit here? or would this point to a configuration setting in azure?

推荐答案

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

Not sure if this is the issue you are facing now BUT you never wait for a result from your async action in the first method Index in your code. MainAsync().ConfigureAwait(false); will immediately return and continue to the next block while the task MainAsync() will start in the background. The catch handler also does nothing because you dont wait f or a result.

选项1(推荐)

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

    return View();
}

选项2,如果由于某些原因您无法使用 async/await

Option 2 if you can't use async/await for some reason

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

    return View();
}

这篇关于GetAsync天蓝色呼叫没有结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆