POST数据到Asana API在C# [英] POST data to Asana API in C#

查看:201
本文介绍了POST数据到Asana API在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用嘉尚API更新和数据添加到Asana。我该怎么做它在C#中?

我得到的数据很好 - 样本code如下:

 字符串apiKey =xxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxx;
VAR REQ = WebRequest.Create(https://app.asana.com/api/1.0/workspaces/xxxxxxxxxxxxxxx/projects);变种AUTHINFO = apiKey +:;
变种EN codedAuthInfo = Convert.ToBase64String(Encoding.Default.GetBytes(AUTHINFO));
req.Headers.Add(授权,基本+ EN codedAuthInfo);
VAR响应=新的StreamReader(req.GetResponse()GetResponseStream()。)ReadToEnd的()。

但我不知道如何发布数据。

他们的文档中的所有例子是使用Python,我有没有经验。

我所接触的体位,但还没有收到回音。
这是我到目前为止所。我得到的最后一行一个400错误

  VAR URL =htt​​ps://app.asana.com/api/1.0/workspaces/xxxxxxxxxxxxxxxxxxx/tasks;
JSON字符串=
    \\数据\\:{+
    \\工作空间\\:nnnnnnnnnnnnnnnn,+
    \\名称\\:\\测试\\,+
    \\注意事项\\:\\测试API POST \\+
    };字节[]字节= Encoding.UTF8.GetBytes(JSON);
VAR REQ = WebRequest.Create(URL)为HttpWebRequest的;req.Method =POST;
req.Co​​ntentLength = bytes.Length;
req.Co​​ntentType =应用/ JSON;变种requestStream = req.GetRequestStream();
requestStream.Write(字节,0,bytes.Length);变种响应= req.GetResponse(); //错误


解决方案

这是我用专门与嘉尚API进行交互。带连接code参数函数将键值对的列表,并把它们转换成以下形式的字符串键=值和放大器;键=值。

在code的发送数据部分是不是我的,但我不记得在那里我从知道了。

我刚开始开发在C#中的API包装,所以这是很轻的测试。它可能不是那样强劲,因为它可以,但我知道一个事实,即它的工作不够好创建体位新的工作空间。

 私人字符串连接codeParameters(ICollection的< KeyValuePair<字符串,字符串>>参数)
    {
        字符串RET =;
        的foreach(KeyValuePair<字符串,字符串>对在参数)
        {
            保留+ =的String.Format({0} = {1}&安培;,pair.Key,pair.Value);
        }
        RET = ret.TrimEnd('和;');        返回RET;
    }    公共字符串的GetResponse(字符串URI,ICollection的< KeyValuePair<字符串,字符串>>的参数,RequestMethods方法= RequestMethods.POST)
    {
        返回的GetResponse(URI,恩codeParameters(参数),法);
    }    公共字符串的GetResponse(URI字符串,字符串数据=,RequestMethods方法= RequestMethods.GET)
    {
        System.Diagnostics.Trace.WriteLine(URI);        //创建请求
        HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(URI);
        要求preAuthenticate = TRUE。
        request.Method = method.ToString()ToUpper的()。
        request.ContentType =应用/的X WWW的形式urlen codeD;        // 登录
        串AUTHINFO = API_KEY +:+; //空密码
        AUTHINFO = Convert.ToBase64String(Encoding.Default.GetBytes(AUTHINFO));
        request.Headers [授权] =基本+ AUTHINFO;        //发送数据
        如果(数据!=)
        {
            字节[] = paramBytes Encoding.ASCII.GetBytes(数据);
            request.ContentLength = paramBytes.Length;
            流reqStream = request.GetRequestStream();
            reqStream.Write(paramBytes,0,paramBytes.Length);
            reqStream.Close();
        }        //获取响应
        尝试
        {
            HttpWebResponse响应=(HttpWebResponse)request.GetResponse();
            返回新的StreamReader(response.GetResponseStream())为ReadToEnd()。
        }
        赶上(引发WebException前)
        {
            HttpWebResponse响应=((HttpWebResponse)ex.Response);
            抛出新的异常(URI +引起了+(INT)response.Status code +错误。\\ n+ response.StatusDescription);
        }
    }

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

这篇关于POST数据到Asana API在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆