1

I'm trying to write a tool for Nextcloud.

It reads some information from another database and then creates a new user in Nextcloud, create a shared folder and copy some files into the new folder. To do that, I'm using Nextcloud's API.

The tool is written in C# and uses HttpWebRequest to send data to the server. Most of the things are working fine but when creating a new user, I can't set the email address of the user. So I tried another Method from the API, to update an existing user.

To update a user I have to send the data in a key - value pair to the server using PUT method. See here for API informations

string mail = "key='email' value='e@mail.us'";
        byte[] data = Encoding.ASCII.GetBytes(mail);

        string requestURL = $"https://nc.example.com/ocs/v1.php/cloud/users/USERNAME";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
        request.ContentType = "text/plain";
        request.Method = "PUT";
        request.ContentLength = data.Length;
        request.KeepAlive = true;
        request.Headers.Add("OCS-APIRequest", "true");
        request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"USERNAME:PASSWORD")));

        Stream dataStream = request.GetRequestStream();
        dataStream.Write(data, 0, data.Length);
        dataStream.Close();
        HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
        Console.WriteLine("" + webResponse.StatusCode);
        StreamReader sr = new StreamReader(webResponse.GetResponseStream());
        String result = sr.ReadToEnd();
        Console.Write(result);

On the Nextcloud docs there is an example to do it

PUT http://admin:secret@example.com/ocs/v1.php/cloud/users/Frank -d key="email" -d value="franksnewemail@example.org"

But I don't know how to create the key - value pair to send it to the server.

Anyone an idea?

Thanks in advance!

r3d007

Edit: maybe it is easier when I give you the correspondending cURL command:

curl -u USER:PW -d key="email" -d value="user@mail.us" -X PUT 'https://nc.example.com/ocs/v1.php/cloud/users/USERNAME' -H "OCS-APIRequest: true"

Again ... Thanks in advance!

r3d007
  • 43
  • 9

2 Answers2

1

I figured it out.

I installed RestSharp via NuGet.

Then this worked for me:

        RestClient rc = new RestClient($"{URL}{UserAPI}/{user}");
        rc.Authenticator = new HttpBasicAuthenticator(Username, Password);
        RestRequest rr = new RestRequest(Method.PUT);
        rr.AddHeader("OCS-APIRequest", "true");
        rr.AddParameter("key", "email");
        rr.AddParameter("value", email);
        var response = rc.Execute(rr);

Thanks for helping!

r3d007
  • 43
  • 9
0

You need to create an object with key value properties

public class foo {

    public string key { get; set; }
    public string mail { get; set; }

}

and serialize that as your data

Adrian Godoy
  • 165
  • 11