401 error accessing valid rest api in c#

-- -- 932 Reputation points
2021-10-21T06:56:16.74+00:00

Hi

I am trying to access rest api from c#.

When I use below url in browser I get the products data as json fine;

https://MyUsername:MyPassword@mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890

When I use url

https://MyUsername:MyPassword@mydomain.com/wp-json/wc/v3/products

and

consumer_key = ck_12345678901234567890 and consumer_secret = cs_12345678901234567890

as Params in Postman then I get the products data as well. So the credentials and url are valid.

However when I try to do this using HttpWebRequest in c# it fails with "The remote server returned an error: (401) Unauthorized" exception. My c# code is below and the exception appears on the last line of code.

The values in HttpWebRequest before the GetResponseAsync call can be seen in attachment. 142366-httpwebrequest.pdf

What am I doing wrong?

Thanks

Regards

string wc_url = "https://MyUsername:MyPassword@mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890";  

HttpWebRequest httpWebRequest = null;  
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url);  

httpWebRequest.AllowReadStreamBuffering = false;  
  
WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,021 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 66,706 Reputation points
    2021-10-22T15:00:10.803+00:00

    Entering the username and password in the the url is a browser feature. The browser removes the values from the url before making the request, and passes them as basic authentication headers.

    So to convert to webclient, remove from url and use basic authentication.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. -- -- 932 Reputation points
    2021-10-22T13:54:55.387+00:00

    Hi

    Using RestSharp below worked fine.

            Dim client = New RestClient("https://mydomain.com/wp-json/wc/v3/products")
            client.Timeout = -1
            client.AddDefaultQueryParameter("consumer_key", "ck_12345678901234567890")
            client.AddDefaultQueryParameter("consumer_secret", "cs_12345678901234567890")
            client.Authenticator = New HttpBasicAuthenticator(MyUsername, MyPassword)
    
            Dim request = New RestRequest(Method.[GET])
    
            Dim response As IRestResponse = client.Execute(request)
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.