2017-02-12 94 views
2

我在XAML应用程序上编写了此简单调用以尝试调用REST服务。使用Autentication令牌进行REST呼叫

程序似乎工作,但我有一个异步方法的问题......我看,我收到令牌,但该方案没有注意到小提琴手..

我怎样才能解决这个问题?是否有最佳做法来做到这一点?

这是文件xaml.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 
using Newtonsoft.Json.Linq; 
using System.Net.Http; 
using System.Net.Http.Headers; 


namespace CallRESTToken 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void button_Click(object sender, RoutedEventArgs e) 
     { 
      try 
      {  
       const string userName = "user"; 
       const string password = "password"; 
       const string apiBaseUri = "http://example.com"; 
       const string apiGetPeoplePath = "/api/values"; 


       //Get the token 
       var token = GetAPIToken(userName, password, apiBaseUri).Result; 

       textBoxtoken.Text = (token); 

       //Console.WriteLine("Token: {0}", token); 

       //Make the call 
       var response = GetRequest(token, apiBaseUri, apiGetPeoplePath).Result; 

       textBox1view.Text = (response); 
       //Console.WriteLine("response: {0}", response); 

       //wait for key press to exit 
       //Console.ReadKey(); 
      } 
      catch (Exception ex) 
      { 

       throw ex; 
      } 
     } 

     private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri) 
     { 
      try 
      {  
       using (var client = new HttpClient()) 
       { 
        //setup client 
        client.BaseAddress = new Uri(apiBaseUri); 
        client.DefaultRequestHeaders.Accept.Clear(); 
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

        //setup login data 
        var formContent = new FormUrlEncodedContent(new[] 
        { 
         new KeyValuePair<string, string>("grant_type", "password"), 
         new KeyValuePair<string, string>("username", userName), 
         new KeyValuePair<string, string>("password", password), 
        }); 

        //send request 
        HttpResponseMessage responseMessage = await client.PostAsync("/token", formContent); 

        //get access token from response body 
        var responseJson = await responseMessage.Content.ReadAsStringAsync(); 
        var jObject = JObject.Parse(responseJson); 
        return jObject.GetValue("access_token").ToString(); 
       } 

      } 
      catch (Exception ex) 
      { 

       throw ex; 
      } 

     } 

     static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath) 
     { 
      try 
      {    
       using (var client = new HttpClient()) 
       { 
        //setup client 
        client.BaseAddress = new Uri(apiBaseUri); 
        client.DefaultRequestHeaders.Accept.Clear(); 
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); 

        //make request 
        HttpResponseMessage response = await client.GetAsync(requestPath); 
        var responseString = await response.Content.ReadAsStringAsync(); 
        return responseString; 
       } 
      } 
      catch (Exception ex) 
      { 

       throw ex; 
      }  
     }  
    } 
} 
+0

什么你所说的“程序没有注意到”意思?当你用调试器执行'GetAPIToken'时会发生什么? – sunside

回答

1

您与.Result阻塞调用混合async背后的代码。

更新事件处理程序以使用异步/等待并删除阻止调用的.Result。事件处理程序是豁免的情况下,允许async void

private async void button_Click(object sender, RoutedEventArgs e) { 
    try { 

     //... code removed for brevity 

     //Get the token 
     var token = await GetAPIToken(userName, password, apiBaseUri); 

     //... code removed for brevity 

     //Make the call 
     var response = await GetRequest(token, apiBaseUri, apiGetPeoplePath); 

     //... code removed for brevity 

    } catch (Exception ex) { 
     throw ex; 
    } 
} 

阅读了Async/Await - Best Practices in Asynchronous Programming

+0

是的...非常感谢你! – stef