Skip to main content
 首页 » 编程设计

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

2024年08月06日5198°冷暖

我有一个正在调用的 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 Controller 时遇到了很大的困难,请有人赐教。

请您参考如下方法:

您需要更改您的方法签名以使用 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 = "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[]