简体   繁体   中英

Looping a method with a response.redirect in a conditional statement

I have a piece of functionality that asks to post on a user's behalf to Facebook if they desire. If a particular checkbox is checked and a button is clicked, it calls a method that posts a preset message on the user's wall. Problem is, there is a redirect that ends the method, but I need it to run through one more time to get to the code that actually posts to the user's wall. Any help would be appreciated.

C#:

protected void btnFbAuth_Click(object sender, EventArgs e)
    {
        var fbAuth = (bool)Session["fbAuth"];
        if (fbAuth != null)
        {
            CheckAuthorization();
        }
    }

    private void CheckAuthorization()
    {
        string app_id = "myAppId";
        string app_secret = "myAppSecret";
        string scope = "publish_stream,manage_pages";

        if (Request["code"] == null)
        {
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", app_id, Request.Url.AbsoluteUri, scope));
        }
        else
        {
            Dictionary<string, string> tokens = new Dictionary<string, string>();
            string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string vals = reader.ReadToEnd();

                foreach (string token in vals.Split('&'))
                {
                    tokens.Add(token.Substring(0, token.IndexOf("=")),
                        token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                }
            }

            string access_token = tokens["access_token"];

            var client = new FacebookClient(access_token);

            client.Post("/me/feed", new { message = "Testing a post on behalf of a user to Facebook wall." });
        }
    }

Since you can't come back into the same POST request after redirects you need to save data somewhere server side (ie session state) and check if there is something to continue from previous request to this page when staring to handle the request.

Note that it may be easier to have separate page that handle just this case - coming back from FB redirect.

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