Code Ratchet
Code Ratchet

Reputation: 6029

Return model from async task after call to web api

I have a web api which I'm calling (this is working correctly)

I call this like so

public ActionResult Index()
    {
        var mod = Checksomething();
        return View();
    }

    public async Task Checksomething()
    {
        try
        {
            var client = new HttpClient();
            var content = new StringContent(JsonConvert.SerializeObject(new UserLogin { EmailAddress = "[email protected]", Password = "bahblah" }));
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await client.PostAsync("http://localhost:28247/api/UserLoginApi2/CheckCredentials", content);

            var value = await response.Content.ReadAsStringAsync();

            // I need to return UserProfile

            var data = JsonConvert.DeserializeObject<UserProfile[]>(value);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

My web api passes back a model called UserProfile, I'm having great difficulty trying to return data back to the Index controller, would someone please enlighten me.

Upvotes: 1

Views: 4393

Answers (1)

Johnathon Sullinger
Johnathon Sullinger

Reputation: 7414

You need to change your method signature to use the generic version of Task

public async Task<ActionResult> Index()
{
    UserProfile[] profiles = await Checksomething();

    if (profiles.Any())
    {
          var user = profiles.First();
          string username = user.FirstName;

          // do something w/ username
    }
    return View();
}

public async Task<UserProfile[]> Checksomething()
{
    try
    {
        var client = new HttpClient();
        var content = new StringContent(JsonConvert.SerializeObject(new UserLogin { EmailAddress = "[email protected]", Password = "bahblah" }));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = await client.PostAsync("http://localhost:28247/api/UserLoginApi2/CheckCredentials", content);

        var value = await response.Content.ReadAsStringAsync();

        // I need to return UserProfile

        return JsonConvert.DeserializeObject<UserProfile[]>(value);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

The returned Task will be unwrapped and your caller will be given the Result of the Task, which in this case will be UserProfile[]

Upvotes: 3

Related Questions