Design

Design
asp.net mvc

2016年3月15日 星期二

OAuth instagram 連線方法 C#

 public ActionResult OAuth()
        {
            code = Request["code"].ToString();
            NameValueCollection parameters = new NameValueCollection();
            parameters.Add("client_id", ConfigurationManager.AppSettings["instagram.clientid"].ToString());
            parameters.Add("client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"].ToString());
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"].ToString());
            parameters.Add("code", code);

            WebClient client = new WebClient();
            var result = client.UploadValues("https://api.instagram.com/oauth/access_token",  parameters);

            //取得json後轉一下string 才不會都是/////////////////////////////////
            var response = System.Text.Encoding.Default.GetString(result);

            //model建立物件後
            // Json反序列化 building model
            var collection = JsonConvert.DeserializeObject(response);
           // 也可以轉JObject然後像下面轉為string取想要用的部分
            var jsResult = (JObject)JsonConvert.DeserializeObject(response);

  
            string accessToken = (string)jsResult["access_token"];
            int id = (int)jsResult["user"]["id"];
            string username = (string)jsResult["user"]["username"];

            Session.Add("name", username);
            Session.Add("InstaSharp.accessToken", collection);
            Session.Add("accessToken", accessToken);
            Session.Add("id", id);

            return RedirectToAction("MyFeed",new { username});
        }

沒有留言:

張貼留言