Search code examples
c#jqueryajaxwebrequest

Make call to REST service from c#


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?


Solution

  • 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);