PostAsJsonAync时unsupported_grant_type

时间:2016-08-16 19:38:12

标签: c# http-post asp.net-web-api2 httpclient

我试图通过c#访问ASP.NET Web API。我编写了API,我可以使用Postman访问它并获得有效的响应。当使用usernamepasswordgrant_type = password时,API会返回access_token和refresh_token。

以下是使用Postman时收到的响应的屏幕截图:

enter image description here

但是,当我尝试使用以下C#代码时:

var userToValidate = new UserToValidate
{
    UserName = "johndoe@mydomain.com",
    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#方面做错事。我错过了什么?

P.S。使用.Result因为调试async代码让我疯狂

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

内容需要进行urlencoded。 这就是它对我有用的方式:

            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;