2017-01-09 58 views
0

我在同一解決方案中創建了兩個項目,一個用於mvc應用程序,另一個用於web api。來自mvc應用程序的Webapi調用

當我從PostMan或任何HttpClient調用我的web api方法時,我能夠收到預期的響應。

但是,當我在MVC應用程序調用相同的方法時,應用程序繼續運行,沒有收到任何響應。 visual studio沒有記錄或顯示特定的例外情況。

我已經複製了我用作參考的代碼。任何幫助將不勝感激。

public class UserFacade 
{ 
    HttpClient _client; 
    string url = "http://localhost:50759/api/v1/login"; 
    public void LoginUser(string userName, string password) 
    { 
     _client = new HttpClient 
     { 
      BaseAddress = new Uri(url) 
     }; 

     _client.DefaultRequestHeaders.Accept.Clear(); 
     _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

     var model = new UserModel 
     { 
      UserName = userName, 
      UserPassword = password 
     }; 

     var userModel = JsonConvert.SerializeObject(model); 
     var content = new StringContent(userModel, Encoding.UTF8, "application/json"); 

     GetUserTask(_client, content).Wait(); 

    } 

    private async Task GetUserTask(HttpClient client, StringContent content) 
    { 
     using (client) 
     { 
      HttpResponseMessage res = await client.PostAsync(url, content); 
      res.EnsureSuccessStatusCode(); 
      if (res.IsSuccessStatusCode) 
      { 
       var response = await res.Content.ReadAsStringAsync(); 

       JavaScriptSerializer JSserializer = new JavaScriptSerializer(); 
       //deserialize to your class 
       //var userResponse = JSserializer.Deserialize<UserResponse>(response); 

      } 
     } 
    } 

} 

只是爲了解我在解決方案中創建了兩個啓動項目並從那裏運行代碼的信息。

回答

1

你正陷入僵局。確保使異步調用時不捕獲背景:

private async Task GetUserTask(HttpClient client, StringContent content) 
{ 
    using (client) 
    { 
     HttpResponseMessage res = await client.PostAsync(url, content).ConfigureAwait(false); 
     res.EnsureSuccessStatusCode(); 
     if (res.IsSuccessStatusCode) 
     { 
      var response = await res.Content.ReadAsStringAsync().ConfigureAwait(false); 
     } 
    } 
} 

注意,我已經加入到這兩個異步調用的.ConfigureAwait(false)

這是說,它是一個完整的廢物要進行異步調用,然後阻止它這樣的:

GetUserTask(_client, content).Wait(); 

你正在殺死絕對異步調用的所有優點。我會強烈建議您使用的代碼的異步版本:

public async Task LoginUser(string userName, string password) 
{ 
    _client = new HttpClient 
    { 
     BaseAddress = new Uri(url) 
    }; 

    _client.DefaultRequestHeaders.Accept.Clear(); 
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

    var model = new UserModel 
    { 
     UserName = userName, 
     UserPassword = password 
    }; 

    var userModel = JsonConvert.SerializeObject(model); 
    var content = new StringContent(userModel, Encoding.UTF8, "application/json"); 

    await GetUserTask(_client, content); 
} 

,然後當然有一個異步動作控制器動作,這將消耗異步方法:

public async Task<ActionResult> Index() 
{ 
    await new UserFacade().LoginUser("user", "secret"); 
    return View(); 
} 
+0

謝謝達林的幫助。 –

相關問題