【问题标题】:nullreference exception when adding session cookie to ServiceStack将会话 cookie 添加到 ServiceStack 时出现 nullreference 异常
【发布时间】:2013-10-08 04:17:43
【问题描述】:

这个问题很大程度上依赖于这里的问题/答案:

Reconnecting to Servicestack session in an asp.net MVC4 application

基本上,我有一个使用 ServiceStack 进行身份验证的 asp.net MVC 应用程序。正如上面提到的问题中所建议的,我将会话 cookie 添加到响应中,然后稍后将其添加到 jsonserviceclient cookie 容器中。

使用此代码在登录屏幕上对用户进行身份验证:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult login(UserModel user)
    {
        try
        {
            var AuthResponse = client.Post(new Auth
            {
                provider = "credentials",
                UserName = user.user_id,
                Password = user.password,
                RememberMe = true
            });

            if (AuthResponse.SessionId != null)
            {
                FormsAuthentication.SetAuthCookie(AuthResponse.UserName, true);
                var response = System.Web.HttpContext.Current.Response.ToResponse();
                response.Cookies.AddSessionCookie(
                    SessionFeature.PermanentSessionId, AuthResponse.SessionId); 

                return Redirect("/Default");
            }
        }
        catch (Exception ex)
        {
            FormsAuthentication.SignOut(); 
            return Redirect("/");
        }
        return View();
    }

但是,我从该行得到一个空引用异常:

response.Cookies.AddSessionCookie(SessionFeature.PermanentSessionId, AuthResponse.SessionId);

堆栈跟踪如下所示:

at ServiceStack.ServiceHost.Cookies.ToHttpCookie(Cookie cookie)
at ServiceStack.ServiceHost.Cookies.AddCookie(Cookie cookie)
at ServiceStack.ServiceHost.Cookies.AddSessionCookie(String cookieName, String cookieValue, Nullable`1 secureOnly)
at FmStoreScreenMvc3.Controllers.AuthController.login(UserModel user) in <project> 51

我想知道此配置是否有任何明显错误。

更新/备注 我已将违规行(抛出 nullref 的位置)更改为:

response.Cookies.AddSessionCookie("foo", "bar", false); 

我仍然遇到同样的错误。只是寻找什么是空的以及为什么

【问题讨论】:

  • 在该行添加一个断点,然后计算出它是什么。
  • 一旦你发现你可以用额外的信息更新问题。例如“为什么 X 为空,我原以为它是 Y”
  • @SeanH 你能用最新版本的 ServiceStack 重试吗?
  • @mythz 更新 3.9.64 -> 3.9.66,结果相同

标签: c# asp.net asp.net-mvc cookies servicestack


【解决方案1】:

代替:

response.Cookies.AddSessionCookie(
  SessionFeature.PermanentSessionId, AuthResponse.SessionId);

试试:

response.SetCookie(SessionFeature.PermanentSessionId, 
    AuthResponse.SessionId, TimeSpan.FromDays(14)));

【讨论】:

  • “方法 'SetCookie' 没有重载需要 1 个参数” - 现在正在研究解决方法
  • 现在似乎可以正常工作了,因为我对代码进行了更多修改。稍作测试后会有反应。谢谢-S
  • @SeanH 好的,刚刚注意到您使用的是 ServiceStack IHttpResponse 而不是底层的 ASP.NET HttpResponse,更新了答案。
  • 这正是我所做的改变:} 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
相关资源
最近更新 更多