Reputation: 623
trying to send a post request (works fine in postman) but keep getting 401 Unauthorised exception in C#. Here is my code:
var httpClient = new HttpClient();
var creds = string.Format("{0}:{1}", "username", "password");
var basicAuth = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(creds)));
httpClient.DefaultRequestHeaders.Add("Authorization", basicAuth);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
requestMessage.Content = new StringContent(postData, Encoding.UTF8, "application/json");
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", "encodedValue==");
var post = httpClient.SendAsync(requestMessage);
post.Wait();
same thing is happening when using HttpWebRequest:
var webReq = (HttpWebRequest)WebRequest.Create(url);
webReq.Headers.Add("Authorization","Basic encodedValue==");
webReq.Method = "POST";
webReq.ContentType = "application/json";
try
{
using (var streamWriter = new StreamWriter(webReq.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)webReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
}
Does any one have any ideas what could I try? PS (encodedValue== is correctly encoded)
Upvotes: 4
Views: 10272
Reputation: 131
Please try this code
using (HttpClient client = new HttpClient())
{
var byteArray = Encoding.ASCII.GetBytes("user:passowrd");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = client.SendAsync(object);
}
Upvotes: 2
Reputation: 331
The HttpClient loses it's headers on redirections.
So make sure, that you use the correct API address. If your API doesn't allow insecure connections but you use "http://your-api-address.xy/" instead of "https://your-api-address.xy/" it will return a redirection and your client loses the headers.
Upvotes: 7