use*_*891 3 c# asp.net-mvc couchdb cloudant
我试图从.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;
}
Run Code Online (Sandbox Code Playgroud)
Get方法是:
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;
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
URL根据API文档:https:// username:password@username.cloudant.com.
我对发生的事情非常困惑,并且在寻找示例时遇到了很多麻烦.谢谢你的帮助!
托马斯
使用HttpClient,您需要执行以下操作以正确进行身份验证(假设您使用基本身份验证):
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(_userName, _password);
HttpClient client = new HttpClient(handler) {
BaseAddress = new Uri(_couchUrl)
};
Run Code Online (Sandbox Code Playgroud)
您不应在_couchUrl中指定用户名/密码 - HttpClient不支持该用户名/密码.
我看不到您的PostAsJsonAsync的实现或您正在构建的完整Url,但是您可以尝试检查/记录response.ReasonPhrase,当出现错误时,可以获得有关出错的提示.
| 归档时间: |
|
| 查看次数: |
1346 次 |
| 最近记录: |