httpclient c# couchdb 未经授权创建数据库
httpclient c# couchdb unauthorized to create database
我在 couchDB 中创建数据库的代码下面有这段代码:
private async void DatabaseCreate()
{
if (!await DatabaseExist())
{
var contents = new StringContent("", Encoding.UTF8, "text/plain");
this.uri = "http://USER:PASSWORD@localhost:5984/item_sn";
var response = await client.PutAsync(this.uri, contents); //set the contents to null but same response.
Console.WriteLine(response.Content.ReadAsStrifngAsync().Result);
}
}
我的问题是它给我的回复是 StatusCode:401,说 "Unauthorized"。我在终端中尝试了 curling,它给了我一个成功的响应。我需要为 httpclient 设置一些先决条件吗?还是我使用了错误的方法。我知道有一些用于 couchDB 的第三方包,但就我而言,我只想使用 C# 的 httpclient。
提前致谢
curl 命令:
curl -X PUT http://USER:PASSWORD@localhost:5984/item_sn
看起来像在 HttpClient class 中,您可以在 HttpClientHandler Class with its Credentials property. Take a look at this answer 中包含凭据。试一试,也许会有用。
这是有效的代码。
public async void DatabaseCreate()
{
if (!await DatabaseExist())
{
var contents = new StringContent("", Encoding.UTF8, "text/plain");
var byteArray = Encoding.ASCII.GetBytes("user:pass");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(byteArray));
this.uri = "http://localhost:5984/databasename";
var response = await client.PutAsync(this.uri, contents);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
}
我在 couchDB 中创建数据库的代码下面有这段代码:
private async void DatabaseCreate()
{
if (!await DatabaseExist())
{
var contents = new StringContent("", Encoding.UTF8, "text/plain");
this.uri = "http://USER:PASSWORD@localhost:5984/item_sn";
var response = await client.PutAsync(this.uri, contents); //set the contents to null but same response.
Console.WriteLine(response.Content.ReadAsStrifngAsync().Result);
}
}
我的问题是它给我的回复是 StatusCode:401,说 "Unauthorized"。我在终端中尝试了 curling,它给了我一个成功的响应。我需要为 httpclient 设置一些先决条件吗?还是我使用了错误的方法。我知道有一些用于 couchDB 的第三方包,但就我而言,我只想使用 C# 的 httpclient。
提前致谢
curl 命令:
curl -X PUT http://USER:PASSWORD@localhost:5984/item_sn
看起来像在 HttpClient class 中,您可以在 HttpClientHandler Class with its Credentials property. Take a look at this answer 中包含凭据。试一试,也许会有用。
这是有效的代码。
public async void DatabaseCreate()
{
if (!await DatabaseExist())
{
var contents = new StringContent("", Encoding.UTF8, "text/plain");
var byteArray = Encoding.ASCII.GetBytes("user:pass");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(byteArray));
this.uri = "http://localhost:5984/databasename";
var response = await client.PutAsync(this.uri, contents);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
}