2015-10-13 122 views
1

我試圖建立一個MVC,請求通過PCL到WebApi。我正在發送獲取請求,並等待響應。郵差返回正確的值。我也不會收到發送異常。這三個項目都採用相同的解決方案。MVC請求到Web Api

PCL

 HttpResponseMessage httpResponse = null; 
     try 
     { 
      httpResponse = await _http.GetAsync("http://localhost:43818/api/values"); 

     } 
     catch (Exception e) 
     { 
      var meessage = e.Message; 
      var stack = e.StackTrace; 

     } 

     if (httpResponse.StatusCode == HttpStatusCode.OK) 
     { 
      string json = await httpResponse.Content.ReadAsStringAsync(); 
     } 

所以,問題是,在PCL,它沒有按通過的await,它卡住。

MVC

 var result = apiClient.GetIndex(); 

網絡API

public class ValuesController : ApiController 
{ 
    // GET api/values 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 
} 

而且,我怎麼在我的MVC等待響應渲染器視圖

+0

什麼是你的PCL的定義是什麼? –

+0

@ErikPhilips便攜式類庫,對不起,我很遺憾 – Robert

+0

你可以粘貼你的PCL及其所有方法的簽名嗎? – din

回答

0

好,所以我找到了最好的溶劑。阻塞線程不是一個好主意。

這是修復

PCL

public async Task<HttpResponseMessage> Register() 
{ 
    HttpRequestMessage request = new HttpRequestMessage 
    { 
     RequestUri = new Uri(_http.BaseAddress, "account/register/"), 
     Method = HttpMethod.Post, 
     Content = new StringContent("{\"Email\": \"[email protected]\",\"Password\": \"Password!1\",\"ConfirmPassword\": \"Password!1\"}", 
     Encoding.UTF8, 
     _contentType 
     ), 
    }; 


     HttpResponseMessage response = new HttpResponseMessage(); 

     try 
     { 
      response = await _http.SendAsync(request, CancellationToken.None); 
     } 
     catch (Exception e) 
     { 
      Debugger.Break(); 
     } 

    return response; 
} 

MVC客戶

public async Task<ViewResult> Index() 
    { 
     var thisTask = await Api.Register(); 

     return View(); 
    } 
3

在你類前庫(PCL),創建方法GetIndex as下面,

public async Task GetIndexAsync() 
    { 
     HttpResponseMessage httpResponse = null; 
     try 
     { 
      _http.BaseAddress = new Uri("http://localhost:43818/"); 
      httpResponse = await _http.GetAsync("api/values"); 

     } 
     catch (Exception e) 
     { 
      var meessage = e.Message; 
      var stack = e.StackTrace; 

     } 

     if (httpResponse.StatusCode == HttpStatusCode.OK) 
     { 
      string json = await httpResponse.Content.ReadAsStringAsync(); 
     } 
    } 

並在如下MVC調用方法,

var result = apiClient.GetIndexAsync().Wait(); 

這既解決了你的問題。

+0

@Robert讓我知道是否它解決了你的問題? –

+0

它的工作,只是你不能將結果存儲在var中,必須設置任務類型,並從那裏獲取結果。謝謝您的回答! – Robert