调用 Web API 后从异步任务返回模型

本文关键字:任务 返回 模型 异步 Web API 调用 | 更新日期: 2023-09-27 18:35:06

我有一个我正在调用的 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 的模型,我在尝试将数据返回到索引控制器时遇到了很大的困难,请有人启发我。

调用 Web API 后从异步任务返回模型

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

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