Page 1 of 1

Sample C# API authentication code

Posted: Thu Sep 10, 2015 10:08 pm
by admin
/// <summary>
/// Main class.
/// Author: Sola Abiodun;
/// </summary>
using System;
using System.Net;
using System.Xml.Linq;
using System.Linq;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

namespace ExpediaBuildMonitor
class MainClass
const string zcommandUrl = "";

public static int Main (string[] args)
WebClient ZCommandWebClient = GetAuthenticatedWebClient ();

var response = ZCommandWebClient.DownloadString(string.Format("{0}/api/devices", zcommandUrl));

Console.WriteLine(string.Format("Response: {0}", response));

return 0;


private static WebClient GetAuthenticatedWebClient(){
JavaScriptSerializer js = new JavaScriptSerializer();
WebClient webClient = new WebClient ();
webClient.Headers.Set(HttpRequestHeader.UserAgent, "zcommand");

var form = js.Serialize (new {Username = "admin", Password = "admin"});
var response = webClient.UploadString(zcommandUrl + "/api/tokenauth", form);
var obj = JObject.Parse (response);

webClient = createAuthorizedWebClient(obj["responseObject"].ToString());
return webClient;

private static WebClient createAuthorizedWebClient(string token){
//Console.WriteLine ("Creating auth with token: " + token);

WebClient webClient = new System.Net.WebClient ();
webClient.Headers.Set(HttpRequestHeader.UserAgent, "zcommand");
webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
webClient.Headers.Add(HttpRequestHeader.Authorization, "Token " + token);
return webClient;


The entire project is attached to this post.
zc auth
(187.63 KiB) Downloaded 436 times

Re: Sample C# API authentication code

Posted: Wed Oct 21, 2015 9:49 am
by merthsoft
Thanks for this! I was struggling a bit until I found this and noticed this line:
webClient.Headers.Set(HttpRequestHeader.UserAgent, "zcommand");
I didn't see anything in the documentation that said I had to set a user agent, but when I did this, it started working!

Re: Sample C# API authentication code

Posted: Wed Oct 21, 2015 11:23 pm
by admin
Yes, the user-agent is required.
We will make this clearer in the documentation.