我正在尝试从 .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。
我对正在发生的事情感到非常困惑,并且很难找到示例。谢谢你的帮助!
托马斯