具有C#中的用户身份验证的cURL

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了具有C#中的用户身份验证的cURL相关的知识,希望对你有一定的参考价值。

我想在c#中执行以下cURL请求:

curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml' \
   -d '<workspace><name>acme</name></workspace>' \
   http://localhost:8080/geoserver/rest/workspaces

我尝试使用WebRequest:

string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);

request.ContentType = "Content-type: text/xml";
request.Method = "POST";
request.Credentials = new NetworkCredential("admin", "geoserver");

byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

WebResponse response = request.GetResponse();
...

但出现错误:(400)错误的请求。

如果我更改了请求凭据并在标题中添加了身份验证:

string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);

request.ContentType = "Content-type: text/xml";
request.Method = "POST";
string authInfo = "admin:geoserver";
request.Headers["Authorization"] = "Basic " + authInfo;

byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

WebResponse response = request.GetResponse();
...

然后我得到:(401)未经授权。

我的问题是:我应该使用另一个C#类,例如WebClient还是HttpWebRequest,还是必须对.NET使用curl绑定?

将感谢所有评论或指导。

答案

HTTP Basic身份验证要求将“ Basic”之后的所有内容都进行Base64编码,因此请尝试

request.Headers["Authorization"] = "Basic " + 
    Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
另一答案

我的问题的解决方案是更改ContentType属性。如果我将ContentType更改为

request.ContentType = "text/xml";

该请求在两种情况下均有效,如果我在上一个示例中也将authInfo转换为Base64String,如建议的[[Anton Gogolev。

另一答案
使用:

request.ContentType = "application/xml"; request.Credentials = new NetworkCredential(GEOSERVER_USER, GEOSERVER_PASSWD);

也可以。第二套验证信息。
另一答案
或者,如果您想使用HttpClient:

var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:geoserver"))); try var client = new HttpClient() DefaultRequestHeaders = Authorization = authValue ; string url = "http://BASE_URL"; client.BaseAddress = new Uri(url); var content = new StringContent("<workspace><name>TestTestTest</name></workspace>", Encoding.UTF8, "text/xml"); var response = await client.PostAsync($"/PATH_TO_API/", content); response.EnsureSuccessStatusCode(); var stringResponse = await response.Content.ReadAsStringAsync(); catch (HttpRequestException ex) Console.WriteLine(ex.Message);

以上是关于具有C#中的用户身份验证的cURL的主要内容,如果未能解决你的问题,请参考以下文章