调用web api后从异步任务返回模型

时间:2014-12-23 05:16:01

标签: c# asp.net-web-api asp.net-mvc-5

我有一个我正在调用的web api(这个工作正常)

我这样称呼

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 = "SomeEmail@Hotmail.com", 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());
        }
    }

我的web api传回一个名为UserProfile的模型,我很难将数据返回到Index控制器,请有人赐教。

1 个答案:

答案 0 :(得分:3)

您需要更改方法签名以使用任务的通用版本

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 = "SomeEmail@Hotmail.com", 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());
    }
}

返回的任务将被解包,您的调用者将获得任务的结果,在这种情况下将是UserProfile[]