Reputation: 165
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:
Upvotes: 4
Views: 37551
Reputation: 165
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);
Upvotes: 5
Reputation: 561
I am using this function to send POST requests with parameters. Where Dictionary<string, string> data
is the key/value as expected by the web service.
public static T PostCast<T>(string url, Dictionary<string, string> data)
{
using (HttpClient httpClient = new HttpClient())
{
var response = httpClient.PostAsync(url, new FormUrlEncodedContent(data)).Result;
return response.Content.ReadAsAsync<T>().Result;
}
}
Upvotes: 1
Reputation: 41
I had the same issue and fixed it by remove the trailing "/" from the URL the HttpClient was posting to.
Upvotes: 0
Reputation: 1137
Try changing your content to the following
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password)
});
Upvotes: 5