0

I am able to successfully connect to an endpoint with javascript but not C#. In the js it returns exactly the correct response but returns 403 in C#. It also seems to fail in python. Does anyone know why this might be?

C# Code:

  static void Main()
    {
        Program P = new Program();
        P.postRequest();
    }
    public void postRequest()
    {

        var apiToken = "MyAPIToken";
        var content = "{TheContent}";

        using (var client = new WebClient())
        {
            string uriString = "URL";
            client.Headers.Clear();
            client.Headers.Add("Content-Type", "application/json");
            client.Headers.Add("Ocp-Apim-Subscription-Key", apiToken);
            byte[] responseArray = client.UploadData(uriString, Encoding.Default.GetBytes(content));
            var response = Encoding.UTF8.GetString(responseArray, 0, responseArray.Length);
        }
    }
  • make sure your header is correct specially in this line `client.Headers.Add("Ocp-Apim-Subscription-Key", apiToken);` – Mahabubul Hasan Feb 03 '20 at 20:07
  • `var apiToken = "";` <-- Probably that, since "" isn't a valid token... – Austin T French Feb 03 '20 at 20:08
  • I removed my actual token when I posted on here, but in my actual testing it is not empty – AbsentmindedInsanity Feb 03 '20 at 20:11
  • @MahabubulHasan I am 99% sure they are correct unless its something to do with bad formatting in regards to client.Headers.Add. I am less familiar with C# overall so stupid little mistakes are possible – AbsentmindedInsanity Feb 03 '20 at 20:14
  • Looks like valid post http procedure, perhaps there is something you are missing in the specific implementation? Have you tried using a packet sniffer like WireShark to compare the JavaScript output headers vs the C# output headers? – Rhaokiel Feb 03 '20 at 20:15
  • 1
    @AbsentmindedInsanity on a side note, try using the newer/ neater way of calling API through `HttpClient` instead of `WebClient`. – Ankit Vijay Feb 03 '20 at 20:16
  • @AbsentmindedInsanity you can enable the trace by using `client.Headers.Add("Ocp-Apim-Trace", "true")` and may be able to debug the cause of the error – Mahabubul Hasan Feb 03 '20 at 20:18
  • 1
    @AbsentmindedInsanity also another thing i just noticed Since you're uploading data shouldn't you need to use header like this `client.Headers.Add("Content-Type","application/x-www-form-urlencoded")` instead of `application/json`?? – Mahabubul Hasan Feb 03 '20 at 20:22

0 Answers0