2017-05-08 24 views
1

My problem爲什麼我有這個Rest Api uri錯誤?

我有我的通用Windows應用程序,我想用rest API來工作。 我總是得到錯誤CS 4032在此:

httpResponseBody = await httpClient.GetStringAsync(requestUri); 

就像你不能調用該方法時,它不是異步。

整個代碼

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 
using Windows.Foundation; 
using Windows.Foundation.Collections; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation; 
using System.Net; 
using Windows.Web.Http; 
namespace UniversalCA 
{ 

    public sealed partial class MainPage : Page 
    { 
     public MainPage() 
     { 
      this.InitializeComponent(); 
      Send();    

     } 

     public string Send() 
     { 
      HttpClient httpClient = new HttpClient(); 
      Uri requestUri = new Uri("http://restapic.azurewebsites.net/WebForm1.aspx?func=dd&hodn=WW"); 
      HttpResponseMessage httpResponse = new HttpResponseMessage(); 
      string httpResponseBody = ""; 
      try 
      { 
       httpResponseBody = await httpClient.GetStringAsync(requestUri); 
      } 
      catch (Exception ex) 
      { 
       httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; 
      } 
      string tt = httpResponseBody.Split('>')[1].Split('<')[0]; 
      return httpResponseBody; 

     } 
    } 
} 
+0

請格式化您的代碼,使其他人可讀 –

+1

爲什麼你有這樣的一行:'HttpResponseMessage httpResponse = new HttpResponseMessage();'?你似乎沒有做任何事情。 – user2657943

回答

1

的問題是,你不能使用await關鍵字不async函數內部。您的Send函數在聲明中沒有async關鍵字。添加async關鍵字就能解決問題

public async Task<string> Send() 
+0

永遠不會編譯,異步方法必須返回'void','Task'或'任務' –

+0

對不起,編輯答案 –

0

只是爲了增加@Ruben Vardanyans答案。

簡單: 添加using System.Threading.Tasks;

您發送添加Wait()關鍵字();調用

public MainPage() 
    { 
     this.InitializeComponent(); 
     Send().Wait();    

    } 
您發送

最後()方法 添加async Task<T>

public async Task<string> Send() 

請看看這個答案調用構造函數內的異步方法。 Call asynchronous method in constructor?

不調用你將有一個編譯器錯誤的方法使用await Send();