I have the following code. It is returning a 401 Unauthorized although it works perfectly on PostMan.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", string.Format("Bearer {0}", token));
var data1 = new { fName = "Sam", lName = "F" };
var result = await client.PostAsync(url, new StringContent(data1.ToString(), Encoding.UTF8, "application/json"));
var response = result.ToString();
What could be wrong here in the above code?
CodePudding user response:
Start adding headers as they appear in Postman, one-by-one to your request. One or more of them is what you're missing.
You can also use Fiddler to verify that how you think your request looks like, is how it actually looks like.
CodePudding user response:
you can try this
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var json = JsonConvert.SerializeObject(data1);
var contentData = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url,contentData);
if it is not working, then you have problem with roles. Your API must be have a role authorization too, not just a token.
