简体   繁体   中英

POST data to Asana API in C#

I am trying to use the Asana API to update and add data to Asana. How do I do it in C#?

I am getting data fine - sample code below:

string apiKey = "xxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxx";
var req = WebRequest.Create("https://app.asana.com/api/1.0/workspaces/xxxxxxxxxxxxxxx/projects");

var authInfo = apiKey + ":";
var encodedAuthInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers.Add("Authorization", "Basic " + encodedAuthInfo);
var response = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();

But I don't know how to POST data.

All the examples in their documentation is using Python which I have no experience with.

I have contacted Asana but have yet to hear back. This is what I have so far. I get a 400 error on the last line

var url = "https://app.asana.com/api/1.0/workspaces/xxxxxxxxxxxxxxxxxxx/tasks";
string json =
    "\"data\": {   " +
    "\"workspace\": nnnnnnnnnnnnnnnn," +
    "\"name\": \"test\"," +
    "\"notes\": \"testing API POST\"" +
    "}";          

byte[] bytes = Encoding.UTF8.GetBytes(json);
var req = WebRequest.Create(url) as HttpWebRequest;

req.Method = "POST";
req.ContentLength = bytes.Length;
req.ContentType = "application/json";

var requestStream = req.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);

var response = req.GetResponse();  //error

This is what I use specifically to interact with the Asana API. The encode parameters function takes a list of key value pairs and converts them into a string of the form "key=value&key=value".

The send data portion of the code is not mine, but I can't remember where I got it from.

I just started developing an API wrapper in C#, so this is very lightly tested. It may not be as robust as it could be, but I know for a fact that it does work well enough to create a new workspace in Asana.

    private string EncodeParameters(ICollection<KeyValuePair<string, string>> parameters)
    {
        string ret = "";
        foreach (KeyValuePair<string, string> pair in parameters)
        {
            ret += string.Format("{0}={1}&", pair.Key, pair.Value);
        }
        ret = ret.TrimEnd('&');

        return ret;
    }

    public string GetResponse(string uri, ICollection<KeyValuePair<string, string>> parameters, RequestMethods method = RequestMethods.POST)
    {
        return GetResponse(uri, EncodeParameters(parameters), method);
    }

    public string GetResponse(string uri, string data = "", RequestMethods method = RequestMethods.GET)
    {
        System.Diagnostics.Trace.WriteLine(uri);

        // create request
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.PreAuthenticate = true;
        request.Method = method.ToString().ToUpper();
        request.ContentType = "application/x-www-form-urlencoded";

        // log in
        string authInfo = API_KEY + ":" + ""; // blank password
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Headers["Authorization"] = "Basic " + authInfo;

        // send data
        if (data != "")
        {
            byte[] paramBytes = Encoding.ASCII.GetBytes(data);
            request.ContentLength = paramBytes.Length;
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(paramBytes, 0, paramBytes.Length);
            reqStream.Close();
        }

        // get response
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return new StreamReader(response.GetResponseStream()).ReadToEnd();
        }
        catch (WebException ex)
        {
            HttpWebResponse response = ((HttpWebResponse)ex.Response);
            throw new Exception(uri + " caused a " + (int)response.StatusCode + " error.\n" + response.StatusDescription);
        }
    }

This is how I do it:

public string SendRequest(WebRequestModel requestModel)
{
    var request = WebRequest.Create(uri);
    var encoding = new UTF8Encoding();
    var requestData = encoding.GetBytes(requestModel.POSTData);

    request.ContentType = requestModel.ContentType;

    request.Method = WebRequestMethods.Http.Post;
    request.Timeout = (300 * 1000); 
    request.ContentLength = requestData.Length;
    // add your header value here
    //request.Headers["myheader"] = "";

    using (var stream = request.GetRequestStream())
    {
          stream.Write(requestData, 0, requestData.Length);
    }
    response = request.GetResponse();

    using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
    {
        result = reader.ReadToEnd();
    }
    return result;
}

My WebRequestModel looks like this:

public class WebRequestModel
{
  public string Url { get; set; }
  public string POSTData { get; set; }
  public string ContentType { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM