我试图从.Net MVC应用程序连接到Cloudant(沙发式数据库).我遵循使用HttpClient使用Web API的准则,如下所示:
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
到目前为止,我有两种方法 – 一种是获取文档,另一种是创建文档 – 两种方法都有错误. 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; }
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; }
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.
我对发生的事情非常困惑,并且在查找示例时遇到了很多麻烦.谢谢你的帮助!
托马斯
解决方法
使用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,当出现错误时,可以获得有关出错的提示.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。