2016-08-16 3 views
1

C#을 통해 ASP.NET 웹 API에 액세스하려고합니다. 필자는 API를 작성했으며 Postman을 사용하여 API에 액세스하여 유효한 응답을받을 수있었습니다. API는 username, passwordgrant_type = password과 함께 표시 될 때 access_token 및 refresh_token을 반환합니다. 나는 시도하고 다음과 같은 C# 코드를 사용할 때, 그러나PostAsJsonAync가 unsupported_grant_type 인 경우

enter image description here

: 나는 오류가

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. async 코드를 디버깅하는 것은 여기에

+0

이 게시물에 해결책이 있습니다. http://stackoverflow.com/questions/29246908/c-sharp-unsupported-grant-type-when-calling-web-api. JSON 대신'application/x-www-form-urlencoded'을 사용해야합니다. – webworm

+0

또한 PostData를 UserToValidate 클래스 대신 KeyValuePair로 전달할 수 있습니다. class List > postData = new List >(); postData.Add (새 KeyValuePair <문자열, 문자열> ("grant_type", "암호"))); postData.Add (새 KeyValuePair ("username", userName)); postData.Add (새 KeyValuePair ("password", password)); ' – Paresh

+0

@ Paresh - 답변을 게시하여 받아 들일 수 있습니까? 그런 식으로 여러 옵션이 있습니다. 감사. – webworm

답변

0

나 너트 드라이브 때문에 .Result을 사용하면 내용이 urlencoded를 할 필요가 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

를 사용하여 토큰을 얻을 수있는 방법이다. 이것이 나를 위해 일한 방법입니다.