【问题标题】:HttpContext.Current.Session["accesstoken"].ToString() is null when value should be set应设置值时,HttpContext.Current.Session["accesstoken"].ToString() 为 null
【发布时间】:2013-05-21 03:52:45
【问题描述】:

我在 Session["accesstoken"] 中设置从 facebook 检索到的 accesstoken。当我尝试检索它时,我被 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) 

附加权限功能:

private void AddAdditionalPermissions() { 字符串 facebook_urlAuthorize_base = "https://graph.facebook.com/oauth/authorize"; 字符串 facebook_urlGetToken_base = "https://graph.facebook.com/oauth/access_token"; 字符串 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);
    }

【问题讨论】:

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


    【解决方案1】:

    我认为您的会话令牌 cookie 丢失了。通过替换

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

    Response.Redirect(urlAuthorize, false);     
    

    看看有没有帮助。

    【讨论】:

    • 感谢 RAS。虽然它解决了会话问题,但它不会重定向用户以提示额外权限。 IE。破坏功能。
    • @MagnusKarlsson,如果你在 Response.Redirect 之后执行:HttpApplication.CompleteRequest()。解决问题了吗?
    • 试过了,没变。我所做的是通过设置一个在昨天使用它时工作的 cookie 来解决问题。今天我启动了,cookie 的行为就像我的会话一样。会不会是 IISExpress 出问题了?
    猜你喜欢
    • 1970-01-01
    • 2016-10-21
    • 2018-11-22
    • 2021-03-31
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2023-03-20
    相关资源
    最近更新 更多