向ServiceStack添加会话cookie时出现nullreference异常

时间:2013-10-07 16:28:01

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

这个问题在很大程度上取决于问题/答案:

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); 

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

1 个答案:

答案 0 :(得分:0)

而不是:

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

尝试:

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