Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access cloudant db using .Net HttpClient

I am attempting to connect to Cloudant (a couch-style DB) from a .Net MVC application. I am following the guidelines for consuming a web API using the HttpClient, as illustrated here: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

I have two methods so far -- one to get a document and one to create a document -- and both have errors. The Get method returns Unauthorized and the Post method returns MethodNotAllowed.

The client is created like this:

    private HttpClient CreateLdstnCouchClient()
    {
        // TODO: Consider using WebRequestHandler to set properties


        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(_couchUrl);

        // Accept JSON
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));


        return client;
    }

The Get method is:

    public override string GetDocumentJson(string id)
    {
        string url = "/" + id;

        HttpResponseMessage response = new HttpResponseMessage();
        string strContent = "";

        using (var client = CreateLdstnCouchClient())
        {
            response = client.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                strContent = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                // DEBUG
                strContent = response.StatusCode.ToString();
                LslTrace.Write("Failed to get data from couch");
            }
        }

        return strContent;
    }

The Post method is:

    public override string CreateDocument(object serializableObject)
    {
        string url = CouchApi.CREATE_DOCUMENT_POST;

        HttpResponseMessage response = new HttpResponseMessage();

        string strContent = "";

        using (var client = CreateLdstnCouchClient())
        {

            response = client.PostAsJsonAsync(url, serializableObject).Result;
            strContent = response.Content.ReadAsStringAsync().Result;
        }

        if (response.IsSuccessStatusCode)
        {
            return strContent;
        }
        else
        {
            LslTrace.Write("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            return response.StatusCode.ToString();
        }
    }

URLs are per the API documentation: https://username:[email protected].

I am very confused by what is going on and having a lot of trouble finding examples. Thanks for your help!

Thomas

like image 729
user2472891 Avatar asked Nov 17 '25 10:11

user2472891


1 Answers

With the HttpClient, you need to do the following to authenticate correctly (assuming you use basic auth):

HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(_userName, _password);
HttpClient client = new HttpClient(handler) {
    BaseAddress = new Uri(_couchUrl)
};

You should not specify the username/password in the _couchUrl - HttpClient doesn't support that.

I can't see your implementation of PostAsJsonAsync or the complete Url your are building, but you can try inspecting / logging response.ReasonPhrase when an error occurs to get a hint as to what went wrong.

like image 160
Will Holley Avatar answered Nov 19 '25 01:11

Will Holley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!