Search code examples
c#.netcurlwebrequest

curl credentials on WebRequest C#


I´m trying to write this call

curl -d @credentials.json -H "Content-Type: application/json" http://128.136.179.2:5000/v2.0/tokens

using WebRequest.

I´m not sure about how should I indicate the credentials:

{"auth":{"passwordCredentials":{"username": "user", "password": "pass"},"tenantName": "tenant"}}

Right now, I´m doing this:

WebRequest request = WebRequest.Create(serverUrl + "tokens");
request.ContentType = "application/json";
request.Method = "GET";
string authInfo = "passwordCredentials:{username:" + username + ", password:" + password + "},tenantName:" + tenantname;
request.Headers["Authorization"] = "Basic " + authInfo;
WebResponse response = request.GetResponse();

Thanks!


Solution

  • Your curl just sends data to that host. It doesn't add it to header. Same thing you shoud do in c#

    var request = WebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "POST"; // I assume your token server accept post request for tokens? It not change for right verb.
    new StreamWriter(request.GetRequestStream()).Write(jsondata);// just for demo. you should also close writer.
    request.ContentLength = jsondata.Length;
    var response = request.GetResponse();
    

    For more information how to use request you can look at msdn https://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx