FB signed_request问题ASP.net c#

时间:2013-05-16 20:41:57

标签: asp.net facebook facebook-c#-sdk facebook-apps

我想在我的asp.net页面上访问signed_request param。 FB正在将请求成功重定向到正确的页面。但是,它是一个GET请求,因此没有传递signed_request参数。

请帮帮我。

尝试使用Request.Form [“signed_request”]读取值,但它是空白的。

如果这是由于配置错误或FB端有些变化,请告诉我。我如何才能实现这一目标。

由于 Syed Adil Umair

1 个答案:

答案 0 :(得分:1)

正如您可能已经知道的那样,当您首次加载页面标签应用程序时,Facebook会向您在应用程序的页面标签URL(或安全页面标签URL)中指定的URL以及signed_request字符串发出POST请求。这就是您的目标网页上的值不为空的原因。但是,当您单击链接以导航到选项卡应用程序内的另一个页面时,它突然变为空。这是应该的,因为你正在发出没有signed_request的GET请求。要使其他页面能够访问signed_request,您需要存储它。我提出以下代码对我有用,但如果有人提供更好的解决方案,我会很高兴听到它:

public static string StoredSignedRequest
{
    get
    {
        string signedRequest = HttpContext.Current.Request["signed_request"];

        // If signed_request is provided, store it
        if (!String.IsNullOrEmpty(signedRequest))
        {
            WriteCookie("fb-app-signed-request", signedRequest);
            return signedRequest;
        }
        else
        {
            return ReadCookie("fb-app-signed-request");
        }
    }
}

public static void WriteCookie(string strCookieName, string strCookieValue)
{
    var hcCookie = new HttpCookie(strCookieName, strCookieValue);
    HttpContext.Current.Response.Cookies.Set(hcCookie);
}

public static string ReadCookie(string strCookieName)
{
    foreach (string strCookie in HttpContext.Current.Response.Cookies.AllKeys)
    {
        if (strCookie == strCookieName)
        {
            return HttpContext.Current.Response.Cookies[strCookie].Value;
        }
    }

    foreach (string strCookie in HttpContext.Current.Request.Cookies.AllKeys)
    {
        if (strCookie == strCookieName)
        {
            return HttpContext.Current.Request.Cookies[strCookie].Value;
        }
    }

    return null;
}

然后,您可以使用JSON解析器来解析StoredSignedRequest的值。就我而言,我使用Newtonsoft:

public static JObject GetSignedRequestJsonObject()
{
    string signed_request = StoredSignedRequest;

    if (String.IsNullOrEmpty(signed_request))
    {
        // If signed_request is null on all pages except the landing page, add the following code to all pages so that it is stored:
        // <input type="hidden" name="signed_request" value="<%= FacebookAppHelper.StoredSignedRequest %>" />
        return null;
    }

    string payload = signed_request.Split('.')[1];
    UTF8Encoding encoding = new UTF8Encoding();
    string decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
    byte[] base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
    string json = encoding.GetString(base64JsonArray);

    return JObject.Parse(json);
}

关键部分是不要忘记将隐藏字段(请参阅上面的注释行)添加到您计划使用页面选项卡应用程序中的GET请求访问的所有页面。