Aaron Aaron - 2 months ago 42
C# Question

Flurl.http PostJsonAsync disappears

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

Answer

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