[英]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.