0

I have code like this:

public async Task<string> getToken()
        {
            string uri = "http://localhost/api/getToken";

            HttpClient client = new HttpClient();
            //client.BaseAddress = new Uri(uri);

            string token = "asfd";
            string baseId = "asfasdf";
            string appVersion = "afsadf";

            string content = "";

            HttpResponseMessage response = null;
            try
            {
                string url = string.Format("{0}?token='{1}'&baseId='{2}'&appVersion='{3}'", uri, token, baseId, appVersion);
                //client.BaseAddress = new Uri(url);
                response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);

                response.EnsureSuccessStatusCode();

                content = await response.Content.ReadAsStringAsync();

            }
            catch (Exception ex)
            {

            }


            return content;
        }

And when I get to the line when is GetAsync called VS turn off debug mode and does not throw any exception. On the server I have breakpoint in the action in controller (mvc web api) and it is not reached. But when I copy url and past it to the browser action in controller is invoked. And when I change my url for some other incorrect url, GetAsync throw exception which is captured in catch. My application is in .net framework 4.5, console application. Maybe I must add any dll ?

2
  • Did you try to put a breakpoint in the catch and on the statement after the call to GetAsync? Which version of VS are you using? Commented Sep 20, 2014 at 10:48
  • Where are you making this call from? A console application? Commented Sep 20, 2014 at 11:19

1 Answer 1

1

You probably aren't waiting for the asynchronous operation to complete. That's why it gets to that aysnc call, the method returns the task that represents the operation and then the application ends.

You need to await the task getToken returns by using await getToken(). If you call getToken from the main method, which can't be async you need to use Task.Wait to wait synchronously:

static void Main()
{
    getToken().Wait();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.