ASP.NET等效于此cURL命令

时间:2011-09-21 22:43:11

标签: c# asp.net curl

我正在使用Twilio API,它提供了PHP和Ruby的示例。我正在一个站点上通过在ASP.NET MVC 3中编码的API发送文本消息,并且使用我对WebRequest对象的有限知识,我能够翻译它:

curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC4840da0d7************f98b20b084/SMS/Messages.xml' \
-d 'From=%2B14155992671' \
-u AC4840da0d7************f98b20b084:f7fc2**************75342

进入这个:

var request =
WebRequest.Create(MessageApiString + "?From=+14*********1&To=" + Phone + "&Body=" + smsCampaign.Message);

var user = "AC4840da0d7************f98b20b084";
var pass = "f7fc2**************75342";

string credentials = String.Format("{0}:{1}", user, pass);
request.Headers.Add("Authorization", credentials);

var result = request.GetResponse();

但它没有进行身份验证,我从他们的API获得了401。 cURL -u命令的等效C#是什么?

更新

        var request =
            WebRequest.Create(MessageApiString + "?From=+14155992671&To=" + Phone + "&Body=" + smsCampaign.Message);

        var cc = new CredentialCache();

        cc.Add(new Uri(MessageApiString), "NTLM", new NetworkCredential("AC4840da0d7************f98b20b084", "f7fc2**************75342"));

        request.Credentials = cc;

        request.Method = "POST";

        var result = request.GetResponse();

仍然有401.任何想法?

更新2

好吧,多亏了下面的答案,我能够通过api,但现在我收到400 Bad Request。是否有更简洁的方法来构建查询字符串以传递此数据?这三个字段为FromToBody

2 个答案:

答案 0 :(得分:6)

尝试包含

 request.Method = "POST";

request.Credentials = new NetworkCredential("username", "password");

答案 1 :(得分:2)

Curl中的-u选项是specify a username and password用于服务器身份验证。

对于C#,这是使用WebRequest.Credentials属性设置的。