最好" curl -u" C#中的等价

时间:2018-06-07 04:02:07

标签: c# .net authorization

当我们有这个curl命令时:

curl -XPUT "https//auth.something.com"
-u "clientId:clientSecret"

如何将其转换为C#?

NetworkCredential myCred = new NetworkCredential(clientKey, clientSecret);

或者:https://stackoverflow.com/a/34649812/5531761

webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + based64;Why should you base64 encode the Authorization header?

或CredentialCache(https://stackoverflow.com/a/3996838/5531761

我的卷曲转换

using(var webClient = new WebClient()){
    webClient.UploadString("https//auth.something.com","PUT","{ \"data\":\"dummy data\" }");
}

2 个答案:

答案 0 :(得分:1)

这是你正在寻找的吗?

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("base address");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("clientId" + ":" + "clientSecret")));

更新:根据更新的问题

我还没试过这个,但你能测试一下吗?

using(var webClient = new WebClient())
{
    webClient.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("clientId" + ":" + "clientSecret")));
    webClient.UploadString("https//auth.something.com","PUT","{ \"data\":\"dummy data\" }");    
}

答案 1 :(得分:0)

如果不能或不会使用HttpClient,您可以使用HttpWebRequest

string postData= "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] data = encoding.GetBytes (postData);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://target.com");
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential ("username", "password");;
request.Method = "PUT";
request.ContentType =  "application/x-www-form-urlencoded";
request.ContentLength = data.Length;    
using (Stream stream = request.GetRequestStream ()) {
    stream.Write (data, 0, data.Length);
}    
var response = (HttpWebResponse)request.GetResponse ();
response.Close ();

MSDN documentation

替代身份验证选项包括:

  • request.Headers["Authorization"] = "Basic " + Convert.ToBase64String*Encoding.ASCII.GetBytes(authInfo));
    HTTP基本身份验证要求“基本”之后的所有内容都是Base64编码的

  • httpWebRequest.Headers.Add("Authorization: OAuth "+acces_token);