HttpContext.Current.Session [“accesstoken”]。当应该设置值时,ToString()为null

时间:2013-05-25 20:43:27

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4

我在Session [“accesstoken”]中设置了从facebook中检索到的accessstoken。当我试图检索它时,我会遇到nullreferenceexception。

为什么?

在我开始使用AddAdditionalPermissions方法之前它确实有效,但我不知道这会如何干扰Session ...?

在调试模式下,我复制了result.ExtraData [“accesstoken”]中的值,并通过formscollection将其添加到代码中(正如您在Facebook.cs中看到的那样)并且令牌有效。我应该使用cookie吗?

AccountController.cs

    public ActionResult ExternalLoginCallback(string returnUrl)
    {
        AuthenticationResult result =   
        OAuthWebSecurity.VerifyAuthentication(
                Url.Action("ExternalLoginCallback",
                new { ReturnUrl = returnUrl }));
        if (!result.IsSuccessful)
        {
            return RedirectToAction("ExternalLoginFailure");
        }

        // Save the accesstoken into session
        Session["accesstoken"] = result.ExtraData["accesstoken"];
        Session["id"] = result.ExtraData["id"];

        if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
        {
            AddAdditionalPermissions();
            return RedirectToLocal(returnUrl);
        }(...etcetera) 

AdditionalPermissions功能:

  

private void AddAdditionalPermissions()           {               string facebook_urlAuthorize_base =“https://graph.facebook.com/oauth/authorize”;               string facebook_urlGetToken_base =“https://graph.facebook.com/oauth/access_token”;               string facebook_AppID =“1secretappIdhere242341”;               string facebook_AppSecret =“1secretcodeheteq4426”;

        string scope = "publish_stream"; 
        string urlAuthorize = facebook_urlAuthorize_base;
        urlAuthorize += "?client_id=" + facebook_AppID;
        urlAuthorize += "&redirect_uri=" + "http://localhost:2730/";
        urlAuthorize += "&scope=" + scope;

        Response.Redirect(urlAuthorize, true);             
    }

Facebook.cs

  

public void PostToFacebook(FormCollection fm)           {               var fb = new FacebookClient();

        fb = new FacebookClient(HttpContext.Current.Session["accesstoken"].ToString());
        var args = new Dictionary<string, object>();
        args["message"] = "abc";

        fb.Post("/me/feed", args);
    }

1 个答案:

答案 0 :(得分:1)

我认为你的会话令牌cookie丢失了。请尝试不要通过替换

来终止当前页面响应
Response.Redirect(urlAuthorize, true);       

Response.Redirect(urlAuthorize, false);     

看看它是否有帮助。