首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#中使用用户身份验证的cURL

在C#中使用用户身份验证的cURL
EN

Stack Overflow用户
提问于 2011-03-01 17:39:49
回答 4查看 24.8K关注 0票数 11

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

代码语言:javascript
复制
curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml' \
   -d '<workspace><name>acme</name></workspace>' \
   http://localhost:8080/geoserver/rest/workspaces

我尝试过使用WebRequest:

代码语言:javascript
复制
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) Bad request。

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

代码语言:javascript
复制
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绑定?

所有的意见或指导将不胜感激。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-03-02 18:24:27

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

代码语言:javascript
复制
request.ContentType = "text/xml";

如果我还像Anton Gogolev建议的那样,在上一个示例中将authInfo转换为Base64String,则该请求在两种情况下都有效。

票数 10
EN

Stack Overflow用户

发布于 2011-03-01 19:08:37

HTTP基本身份验证将"Basic“之后的所有内容都重新编码为base64编码,因此请尝试

代码语言:javascript
复制
request.Headers["Authorization"] = "Basic " + 
    Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
票数 12
EN

Stack Overflow用户

发布于 2012-06-21 20:51:16

使用:

代码语言:javascript
复制
request.ContentType = "application/xml";

request.Credentials = new NetworkCredential(GEOSERVER_USER, GEOSERVER_PASSWD);

也是有效的。第二个设置身份验证信息。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5152723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档