Issue
I use EF to create WebAPi. Everything seems fine. I add Swagger into the app. I login user from Xamarin Forms sang ASP.NET Identity using OAuth.
public async Task LoginAsync(string userName, string password)
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("phoneNum", userName),
new KeyValuePair<string, string>("passwordUs", password),
};
var request = new HttpRequestMessage(
HttpMethod.Post, "https://xxxxxxx/api/Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
Debug.WriteLine(content);
}
However, I get the error: Unsupported Media Type
. Meanwhile I checked on Swagger, Ok
Please help me with the solution. Thanks
Update I've added:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
I checked on Swagger and Postman both ok
However, I get the error: Unsupported Media Type
Solution
From the Curl and Postman in the shown images, the API most likely expects JSON yet the shown code is sending URL encoded form data.
//...
request.Content = new FormUrlEncodedContent(keyValues);
//...
Send the supported content type (application/json) and that should solve your problem.
For example
static HttpClient client = new HttpClient();
public async Task LoginAsync(string userName, string password) {
var model = new {
phoneNum = userName,
passwordUs = password
};
string json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, "application/json");
string url = "https://xxxxxxx/api/Token";
var response = await client.PostAsync(url, content);
var responseBody = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseBody);
}
The above refactoring of the original code creates a model with the desired members and serializes it to JSON using JSON.Net.
That content is what will be posted to the API as the request body in the expected format.
Answered By - Nkosi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.