[英]CouchDB connection
我尝试连接到CouchDB,但是似乎在任何地方都找不到关于它的清晰解释。 这是我在C#中尝试过的方法,但是它什么也没做。
using (var db = new MyCouch.Client("http://127.0.0.1:5984/db"))
{
var db = "{'_id': '1', '$doctype': 'db', 'name': '1'}";
var response = db.Documents.Post(db);
Console.Write(response.GenerateToStringDebugVersion());
}
有人可以向我解释如何连接以及如何简单地插入数据吗?
连接到CouchDB的简单方法是使用System.Net.Http.HttpClient并绕开客户端库本身(尽管有一些不错的库)。
由于CouchDB API是HTTP,因此您将需要使用主要方法GET,PUT POST和DELETE,因此下面提供了一个包装PUT的通用方法示例,该示例使用本机JSON序列化器接受POCO模型T并将其写为文档(为了清楚起见,省略了序列化异常处理)
public async Task<R> Put<T, R>(T docObject)
{
string DbName = "demodb";
string NewDocId = "newDocId";
// Valid paths, methods and response codes are documented here: http://docs.couchdb.org/en/stable/http-api.html
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://server:5984/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// NB: PutAsJsonAsync is an extension method defined in System.Net.Http.Formatting
var response = await httpClient.PutAsJsonAsync(DbName + "/" + NewDocId, docObject);
R returnValue;
if (response.StatusCode == HttpStatusCode.OK)
{
returnValue = await response.Content.ReadAsAsync<R>();
}
// Check the docs for response codes returned by each method.
// Do not forget to check for HttpStatusCode.Conflict (HTTP 409) and respond accordingly.
}
}
为了完成示例,返回类型R应该是可以反序列化从CouchDB返回的JSON响应的属性的内容,例如
public class CreateResponse
{
// use of JsonPropertyAttribute is supported on properties if needed.
public bool ok { get; set; }
public string id { get; set; }
public string rev { get; set; }
public string error { get; set; }
public string reason { get; set; }
}
如果使用基本身份验证,则可以在服务器Url之前添加凭据,例如: http:// user:pass @ server /如果使用Cookie身份验证,请使用新的CookieContainer设置HttpClientHandler并将处理程序传递给HttpClient构造函数。
最后两个注意事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.