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

问题描述 投票:11回答:4

我想在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绑定?

将感谢所有评论或指导。

c# .net authentication curl geoserver
4个回答
12
投票

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

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

9
投票

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

request.ContentType = "text/xml";

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


2
投票
使用:

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

也可以。第二套验证信息。

0
投票
或者,如果您想使用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); }

© www.soinside.com 2019 - 2024. All rights reserved.