Click here to Skip to main content
15,938,848 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a login method where I am trying to pass a token into the header along with the credentials and the format "application/json" but unfortunately I am getting a 415 unsupported media type and I don't understand why.I understand the fact that the format is wrong,but why?.For the server-side I am using .net core and the authentication method there works perfectly.This is the login method in Xamarin:
public async Task<Token> Login(string email, string password)
          HttpClient client = new HttpClient();
          var Loginurl = "";
          Token returnResult = default(Token);
          var uri = new Uri(string.Format("{0}{1}", Loginurl, "Token"));


              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
              client.DefaultRequestHeaders.Add("Authorization", "Bearer" + returnResult);
              client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", email, password))));

              List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
              requestData.Add(new KeyValuePair<string, string>("email", email));
              requestData.Add(new KeyValuePair<string, string>("password", password));
              requestData.Add(new KeyValuePair<string, string>("grant_type", "password"));
              FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);
              //Request Token
              var request = await client.PostAsync(uri, requestBody);
              if (request.IsSuccessStatusCode)
                  var response = await request.Content.ReadAsStringAsync();
                  returnResult = JsonConvert.DeserializeObject<Token>(response);
                  await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new UsersPage());
                  await App.Current.MainPage.DisplayAlert("Something went wrong!", "Your credentials are not good", "ok", "cancel");

          catch (Exception ex)
              string e = ex.InnerException.ToString();

          return returnResult;

Can someone please help me in this matter?Any help would be appreciated!

What I have tried:

I have also tried with StringContent,but I got 400 error "Bad Request".This is what I tried:
var client = new HttpClient();
        var json = JsonConvert.SerializeObject(keyValue);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(urlLogin,content);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900