I am successful using Postman doing a post for authentication. However, I can't seem to get it to work from C# and am getting a 401 error. The password and username are verified the same as in Postman. How can I do it?
Here is my code:
var url = AppConstants.ApiLoginUrl;
var uriRequest = new Uri(url);
string httpResponseBody;
using (var httpClient = new Windows.Web.Http.HttpClient())
{
var content = new HttpStringContent(string.Format("username={0}&password={1}", email, password), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
try
{
var httpResponse = await httpClient.PostAsync(uriRequest, content);
...
}
}
Here are the settings in Postman for header and body.
Now using this code for the content parameter:
var content = new HttpFormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password)
});
Upon a closer look, it appears the username is encoded in Fiddler for both the Postman and code requests. So, my theory about using an encoded username is not quite right. Here at the snapshots of the requests from Fiddler... Is is possible?
Postman headers:
Code headers:
Raw View Postman * showing encoded username field:
Raw view code:
Try changing your content to the following
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password)
});
My understanding is that for UWP applications Windows.Web.Http.HttpClient() is the recommended way to do this, plus make sure your URL's do not have typos. :)
var url = AppConstants.ApiLoginUrl;
var uriRequest = new Uri(url);
var content = new HttpFormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password)
});
using (var httpClient = new Windows.Web.Http.HttpClient())
{
try
{
var httpResponse = await httpClient.PostAsync(uriRequest, content);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With