POST data to Asana API in C#

*爱你&永不变心* 提交于 2019-12-12 03:37:58

问题


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

回答1:


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);
        }
    }



回答2:


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; }
}


来源:https://stackoverflow.com/questions/13802411/post-data-to-asana-api-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!