卷曲在C#中的用户身份验证 [英] cURL with user authentication in C#

查看:233
本文介绍了卷曲在C#中的用户身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#中的以下卷曲的请求:

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#类像Web客户端或HttpWebRequest的还是必须要使用.NET的卷曲绑定

My question is: Should I use another C# class like WebClient or HttpWebRequest or do I have to use the curl bindings for .NET?

所有评论和指导,将AP preciated。

All comments or guidance would be appreciated.

推荐答案

解决我的问题是改变的的ContentType 的属性。如果我将contentType改为

The solution to my question was changing the ContentType property. If I change the ContentType to

request.ContentType = "text/xml";

要求工作在这两种情况下,如果我也转换的 AUTHINFO 的在最后一个例子例如安东Gogolev 提出了Base64String。

the request works in both cases, if I also convert the authInfo to a Base64String in the last example like Anton Gogolev suggested.

这篇关于卷曲在C#中的用户身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆