nullreference exception when adding session cookie

2019-08-14 00:57发布

问题:

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