API call successfully from external client but not from c#

1k Views Asked by At

I need to call client API-HTTPS (GET) with some specific headers

Accept:application/json,application/vnd.error+json
Date:2018-10-03T06:52:48Z
Authorization:<SECRETKEY>

In this scenario when I try to call it from client like Postman or Advanced REST client, API give proper result. But the same thing I tried with C# code which generates 401-Unauthorized errorcode.

For example If I'm using postman code for RestSharp (C#). It won't work from my code. Postman screenshot:
Postman screenshot

Even I tried the same with HttpWebRequest and HttpClient too. But no luck.

Code which postman provided from code section is as below with some confidential information which I can't expose.

var client = new RestClient("https://**CLIENT_API_PATH**");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "ef8c2a79-a501-4cef-aa2e-bacdc9d3a922");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "**SECRET_KEY**");
request.AddHeader("Date", "2018-10-03T06:52:48Z");
request.AddHeader("Accept", "application/json,application/vnd.error+json");
IRestResponse response = client.Execute(request);

In above code 3 parameters are compulsory and have to pass for successful call to API.

  1. Date with the above mentioned format only.

  2. Accept with above mentioned string only.

  3. Authorization with specific authentication (custom by client).

As per suggested comment I also add fiddler data from the call.

  1. Postman request fetch from fiddler fiddler screenshot
  2. C# api call code request from fiddler fiddler screenshot
  3. C# code debug result visual studio debug screenshot
1

There are 1 best solutions below

3
On

Try this.

public static string Get(Uri uri, string token)
{
    string responseString = string.Empty;
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

    request.Method = "GET";
    request.ContentType = "application/json;charset=utf-8";
    request.Headers.Add("Authorization", string.Format("Bearer {0}", token));

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader responseReader = new StreamReader(responseStream);
            responseString = responseReader.ReadToEnd();
        }
    }
    return responseString;
}