Reputation: 149
I am able to make the following web request via an jQuery AJAX call:
params = { "session[email]": "[email protected]", "session[password]": "password" }
var token;
$.ajax({
type: "POST",
url: "https://api.publicstuff.com:443/app/auth/sign_in",
dataType: 'json',
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Token token=123456" );
},
data: params,
success: function (response) {
if (response.success) {
alert('Authenticated!');
token = response.token;
}
});
When trying to make the same call from c# I am unable to successfully contact the remote server as I am receiving errors stating that the remote server cannot be found. Here is the code that I'm trying to get working in c#:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Token token=123456");
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("session[email]", "[email protected]"),
new KeyValuePair<string, string>("session[password]", "pw")
};
var content = new FormUrlEncodedContent(pairs);
var response = client.PostAsync("https://api.publicstuff.com:443/app/auth/sign_in", content).Result;
Any pointers on how to make the same web service in c# or what I'm doing wrong here?
Upvotes: 1
Views: 975
Reputation: 149
I got this working using RestSharp. Here is the code that worked for me:
var client = new RestClient("https://api.publicstuff.com:443/app/auth/sign_in");
var request = new RestRequest(Method.POST);
request.AddParameter("session[email]", "[email protected]");
request.AddParameter("session[password]", "password");
request.AddHeader("Authorization", "Token token=123456");
IRestResponse response = client.Execute(request);
Upvotes: 0
Reputation: 136124
The big difference between your two ways is that the former makes the http request from your machine, whereas the c# code makes it from the server running your app.
It is quite possible that your machine can resolve api.publicstuff.com
, but that the machine running the c# code cannot (Behind a firewall, or no public access at all).
Upvotes: 0