2016-08-16 67 views
1

我想通過c#訪問ASP.NET Web API。我編寫了API,並且能夠訪問它並使用Postman獲得有效的響應。當呈現usernamepasswordgrant_type = password時,API返回access_token和refresh_token。unsupported_grant_type當PostAsJsonAync

下面是我用郵差當接收響應的屏幕截圖:

enter image description here

然而,當我嘗試使用下面的C#代碼:

var userToValidate = new UserToValidate 
{ 
    UserName = "[email protected]", 
    Password = "Abc123!", 
    grant_type = "password" 
}; 

using (var client = new HttpClient()) 
{ 
    client.BaseAddress = new Uri("http://localhost:4321"); 
    client.DefaultRequestHeaders.Accept.Clear(); 
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    HttpResponseMessage response = client.PostAsJsonAsync("oauth/token", userToValidate).Result; 
    content = response.Content.ReadAsStringAsync().Result; 
} 

我得到一個錯誤... {"error":"unsupported_grant_type"}

我必須在C#方面做錯了什麼NGS。我錯過了什麼?

P.S.使用.Result因爲調試async代碼驅使我堅果

+0

我在這個SO帖子中找到了解決方案。 http://stackoverflow.com/questions/29246908/c-sharp-unsupported-grant-type-when-calling-web-api。必須使用'application/x-www-form-urlencoded'而不是JSON。 – webworm

+0

此外,您可以傳遞PostData作爲KeyValuePair而不是UserToValidate類'List > postData = new List >(); postData.Add(new KeyValuePair (「grant_type」,「password」)); postData.Add(new KeyValuePair (「username」,userName)); postData.Add(new KeyValuePair (「password」,password)); ' – Paresh

+0

@Paresh - 你可以發表一個答案,我會接受iy。這樣有多種選擇。謝謝。 – webworm

回答

0

這裏是你如何能得到令牌使用JSON

 using (var client = new HttpClient()) 
     { 
      var email = "xyz" 
      var password = "abc"; 
      var clientId = "123" 
      var clientSecret = "456"; 

      client.BaseAddress = new Uri(baseUrl); 

      // We want the response to be JSON. 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      // Build up the data to POST. 
      List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>(); 

      postData.Add(new KeyValuePair<string, string>("grant_type", "password")); 
      postData.Add(new KeyValuePair<string, string>("client_id",  clientId)); 
      postData.Add(new KeyValuePair<string, string>("client_secret", clientSecret)); 
      postData.Add(new KeyValuePair<string, string>("username",  email)); 
      postData.Add(new KeyValuePair<string, string>("password",  password)); 



      // Post to the Server and parse the response. 
      HttpResponseMessage response = await client.PostAsJsonAsync("Token", postData); 
      string jsonString   = await response.Content.ReadAsStringAsync(); 
      object responseData   = JsonConvert.DeserializeObject(jsonString); 

      // return the Access Token. 
      accessToken = ((dynamic)responseData).access_token; 
     } 

     return accessToken; 
0

內容需要進行url編碼。 這是如何工作對我來說:

  var httpClient = new HttpClient(); 
      httpClient.DefaultRequestHeaders.Add("X-Tenant", xTenant); 
      var stringContent = String.Concat("grant_type=password&username=", HttpUtility.UrlEncode(username), 
       "&password=", HttpUtility.UrlEncode(password)); 
      var httpContent = new StringContent(stringContent, Encoding.UTF8, "application/x-www-form-urlencoded"); 
      var postTask = httpClient.PostAsync(apiLoginUrl, httpContent); 
      postTask.Wait(); 
      var postResult = postTask.Result; 
      var content = postResult.Content.ReadAsStringAsync().Result; 
      dynamic jsonRes = JsonConvert.DeserializeObject(content); 
      string access_token = jsonRes.access_token;