Marcus Aurelius
Marcus Aurelius

Reputation: 99

httpclient c# couchdb unauthorized to create database

I have this code below code to create a database in couchDB:

private async void DatabaseCreate()
        {
            if (!await DatabaseExist())
            {
                var contents = new StringContent("", Encoding.UTF8, "text/plain"); 
                this.uri = "http://USER:PASSWORD@localhost:5984/item_sn";
                var response = await client.PutAsync(this.uri, contents); //set the contents to null but same response.
                Console.WriteLine(response.Content.ReadAsStrifngAsync().Result); 
            }
        }

My problem is that it is giving me a response with StatusCode:401, saying "Unauthorized". I tried curling it in the terminal and it gives me a successful response. Is there some preconditions I need to set for the httpclient? Or am I using the wrong method. I know there are some third party package for couchDB but for my case I just want to use C#'s httpclient.

Thanks in advance

curl command:

curl -X PUT http://USER:PASSWORD@localhost:5984/item_sn

Upvotes: 2

Views: 515

Answers (2)

Marcus Aurelius
Marcus Aurelius

Reputation: 99

Here's the code that worked.

public async void DatabaseCreate()
            {
                if (!await DatabaseExist())
                {
                    var contents = new StringContent("", Encoding.UTF8, "text/plain");
                    var byteArray = Encoding.ASCII.GetBytes("user:pass");
                    client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(byteArray));
                    this.uri = "http://localhost:5984/databasename";
                    var response = await client.PutAsync(this.uri, contents);
                    Console.WriteLine(response.Content.ReadAsStringAsync().Result); 
                }
            }

Upvotes: 1

Megidd
Megidd

Reputation: 7989

Looks like in HttpClient class you can include credentials with HttpClientHandler Class with its Credentials property. Take a look at this answer. Try it, maybe that would work.

Upvotes: 1

Related Questions