0

I am in a situation where I know I can connect to an endpoint (using Postman chrome app) but I get an authentication error when I attempt it through HttpClient executing as WebJob on Azure.

public  string ScanEndPoint()
        {
            string result;


            using (var client = new HttpClient())
            {
                var requestContent = new MultipartFormDataContent();

                var url = $"{Host}/{Path}";

                requestContent.Add(new StringContent("*"), Version);
                requestContent.Add(new StringContent("***"), Reference);
                requestContent.Add(new StringContent("********"), Password);
                var response =  client.PostAsync(url, requestContent).Result;
                result = response.Content.ReadAsStringAsync().Result;
            }
            return result;
        }

The MultipartFormData is because I have to post the credentials in the body and not as headers. Clicking on the code link in Postman shows:

POST /*************.php HTTP/1.1
Host: *****-*******.****.******
Cache-Control: no-cache
Postman-Token: b574e803-1873-d7dd-ff10-bfc509991342
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="*"

**
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="***"

****
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="*********"

********************************
------WebKitFormBoundary7MA4YWxkTrZu0gW--

What steps do I need to take to replicate that postman request so that it works in code?

Jayendran
  • 9,638
  • 8
  • 60
  • 103
onesixtyfourth
  • 744
  • 9
  • 30

1 Answers1

0

This is what we had to do to get it working:

 using (var client = new HttpClient(handler: clientHandler, disposeHandler: true))
            {
                client.BaseAddress = new Uri(Host);

                var url = $"{Path}";
                var parameters = new Dictionary<string, string> {
                    { "V", Version },
                    { "ref", Reference },
                    { "password", Password }
                };

                var encodedContent = new FormUrlEncodedContent(parameters);

                var response = client.PostAsync(url, encodedContent).Result;
                result = response.Content.ReadAsStringAsync().Result;
            }
            return result;

The handler sets up a proxy for local debug which should be irrelevant on Azure but I can remove it if that proves to be wrong.

Most of the posts I read about this suggested the same approach as @Jayendran pointed to. Any ideas on what the differences might be?

Note: we also had to re-arrange the Host and path so that the Host ended with a "/"

onesixtyfourth
  • 744
  • 9
  • 30