3

我正在尝试从 .Net MVC 应用程序连接到 Cloudant(沙发式数据库)。我遵循使用 HttpClient 使用 Web API 的指南,如下所示: http ://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-网络客户端

到目前为止,我有两种方法——一种是获取文档,一种是创建文档——两者都有错误。Get 方法返回 Unauthorized,Post 方法返回 MethodNotAllowed。

客户端是这样创建的:

    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;
    }

获取方法是:

    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;
    }

Post方法是:

    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();
        }
    }

URL 来自 API 文档:https://username:password@username.cloudant.com

我对正在发生的事情感到非常困惑,并且很难找到示例。谢谢你的帮助!

托马斯

4

1 回答 1

7

使用 HttpClient,您需要执行以下操作才能正确进行身份验证(假设您使用基本身份验证):

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

您不应该在 _couchUrl 中指定用户名/密码 - HttpClient 不支持。

我看不到您对 PostAsJsonAsync 的实现或您正在构建的完整 Url,但您可以尝试检查/记录 response.ReasonPhrase 时出现错误以获取有关问题的提示。

于 2013-06-11T09:47:47.833 回答