cURL 使用 C# 中的用户身份验证 [英] cURL with user authentication in C#
问题描述
我想在 c# 中执行以下 cURL 请求:
I want to do the following cURL request in c#:
curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml'
-d '<workspace><name>acme</name></workspace>'
http://localhost:8080/geoserver/rest/workspaces
我尝试过使用 WebRequest:
I have tried using a 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) 错误的请求.
But I get an error: (400) Bad request.
如果我更改请求凭据并在标头中添加身份验证:
If I change the request credentials and add the authentication in the header:
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) 未经授权.
Then I get: (401) Unauthorised.
我的问题是:我应该使用另一个 C# 类,如 WebClient 或 HttpWebRequest,还是必须使用 .NET 的 curl 绑定?
My question is: Should I use another C# class like WebClient or HttpWebRequest or do I have to use the curl bindings for .NET?
感谢所有评论或指导.
推荐答案
我的问题的解决方案是更改 ContentType 属性.如果我将 ContentType 更改为
The solution to my question was changing the ContentType property. If I change the ContentType to
request.ContentType = "text/xml";
请求在这两种情况下都适用,如果我也在最后一个示例中将 authInfo 转换为 Base64String,就像 Anton Gogolev 建议的那样.
the request works in both cases, if I also convert the authInfo to a Base64String in the last example like Anton Gogolev suggested.
这篇关于cURL 使用 C# 中的用户身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!