1

I have a class that is posting to an API which is working in my unit tests but not my MVC controller.

In the tester the following line works just fine but when call it in my MVC application I cannot step beyond the following line.

public async Task<string> post( object values )       
    {
        using (var client = new HttpClient())
        {
            try
            {
                var responseString = await address.PostJsonAsync(values).ReceiveString();
                return responseString; //Never reaches this line while in MVC.

            }
            catch (Exception e)
            {
                //Console.Error.WriteLine(e.Message);
                return "";
            }
        }
    }
Aaron
  • 1,042
  • 2
  • 12
  • 30
  • Not sure I follow, I think some more details are needed here. When you say you can't step beyond that line, does it just hang? Is there some sort of exception thrown? – Todd Menier Nov 14 '15 at 15:45
  • I've update my code snippet. I make it to the PostJsonAsync when stepping through the code but never to _either_ of the return statements. – Aaron Nov 16 '15 at 22:26

2 Answers2

3

Another coworker help me find the problem. It had to do with async/await/sync. Changing to return the Result right from the call fixed the problem.

    public string post( object values ) 
    {
        try
        {
            var responseString = address.PostJsonAsync(values).ReceiveString().Result;
            return responseString;
        }
        catch (Exception e)
        {
            //Console.Error.WriteLine(e.Message);
            return "";
        }            
    }
Aaron
  • 1,042
  • 2
  • 12
  • 30
  • 1
    Why are you having a using block with the `HttpClient`? I can not spot any usage of it, appears to be unrelated. – cel sharp Sep 22 '16 at 12:20
1

Be use to use Flurl.Http package, not only Flurl package

Get it on NuGet: PM> Install-Package Flurl.Http

Or get just the stand-alone URL builder without the HTTP features: PM> Install-Package Flurl

https://github.com/tmenier/Flurl

Community
  • 1
  • 1
Chris
  • 1,122
  • 1
  • 12
  • 14