I am building a C# ASP.Net Core minimal API consuming app. It POSTs a new record to an external Web API site. I am putting Basic Authentication with UserID and Password in the header, and including the necessary payload. I’m getting back a 401 Unauthorized reponse.
If I submit the same credentials, authorization and payload via POSTMAN, I get a 200 successful response, so I know its all credentials, etc. are correct. For the life of me, I can’t figure out why this code doesn’t work. Any and all help would be appreciated, as I’m new to Web API calls.
Here is my code:
string guestPayload = "{"ID":"2222-639","GuestPermissions":[{"Action":"A","PermissionStart":"2024-07-09T00:00:00","Reason":"New Guest"}]}";
HttpClient client = new HttpClient();
var username = "CorrectUserID";
var password = "CorrectPassword";
var url = "https://apiSiteToConsume.com/api/";
var requestUri = "guest/permissions";
Uri baseUri = new Uri(url);
using (client = new HttpClient { BaseAddress = new Uri(baseUri.ToString()) })
{
var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes("username:password"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authString);
var response = await client.PostAsync(requestUri, new StringContent(guestPayload));
}