无法使用标头正确进行身份验证(HttpClient)

时间:2017-01-17 12:49:18

标签: c# json authentication xamarin

我检查了很多论坛,但我无法使其发挥作用。我正在尝试使用标头进行身份验证,以便在身份验证成功时返回JSON字符串。在Postman中,我只是在标题中使用了Get方法usernamepassword来获取JSON数据。我需要做哪些更改才能使我的后续C#代码实现相同的功能?我想我甚至没有将用户名和password添加到headers

  public async Task<string> LogMeIn(string username, string password)
        {
            var client = new HttpClient {
                BaseAddress = new Uri("http://x.com")
            };

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var content = new FormUrlEncodedContent(new[] {

                new KeyValuePair<string,string>("grant_type","password"),
                       new KeyValuePair<string,string>("Username ", username),
                       new KeyValuePair<string,string>("Password", password)
                    });

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var response = await client.PostAsync("/login", content); //should it be GetAsync?


            var jsonResp = await response.Content.ReadAsStringAsync();

            var jsonResult = JsonConvert.DeserializeObject<JsonResult>(jsonResp); //JsonResult = class for json

            return jsonResult.token;
       }
    }

0 个答案:

没有答案