nullreference exception when adding session cookie to ServiceStack

走远了吗. 提交于 2019-12-11 07:49:21

问题


This question relies quite a bit on the question/answer here:

Reconnecting to Servicestack session in an asp.net MVC4 application

Basically, I have an asp.net MVC application that is using ServiceStack for authentication. As suggested in the question mentioned above I am adding a session cookie to the response and then adding it to the jsonserviceclient cookie container later.

Using this code to authenticate the user at the login screen:

    [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();
    }

However, I am getting a null ref exception from the line:

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

The stack trace looks like:

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

I'm wondering if anything seems obviously wrong with this configuration.

Update/note I have changed the offending line (Where the nullref is thrown) to:

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

I still get the same error. Just hunting for what is null and why


回答1:


Instead of:

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

Try:

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


来源:https://stackoverflow.com/questions/19229934/nullreference-exception-when-adding-session-cookie-to-servicestack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!