簡體   English   中英

調用web api后從異步任務返回模型

[英]Return model from async task after call to web api

我有一個我正在調用的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控制器,有人請賜教。

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

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[]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM