C#中使用C#进行用户身份validation

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

curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml' \ -d 'acme' \ 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("my_workspace"); Stream reqstr = request.GetRequestStream(); reqstr.Write(buffer, 0, buffer.Length); reqstr.Close(); WebResponse response = request.GetResponse(); ... 

但是我收到一个错误:(400)请求不好。

如果我更改请求凭据并在标头中添加身份validation:

 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("my_workspace"); Stream reqstr = request.GetRequestStream(); reqstr.Write(buffer, 0, buffer.Length); reqstr.Close(); WebResponse response = request.GetResponse(); ... 

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

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

所有评论或指导将不胜感激。

HTTP基本身份validation要求“基本”之后的所有内容都是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); 

也有效。 第二个设置认证信息。