1
\$\begingroup\$

first time poster here.

I'm creating a session cookie which should expire after 30 minutes of user inactivity. I've added the following code to the base controllers OnActionExecuted method.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var sessionCookie = Request.Cookies[COOKIE_VALUE];

        if (sessionCookie == null)
        {
            sessionCookie = new HttpCookie(COOKIE_VALUE)
            {
                Expires = DateTime.Now.AddMinutes(30)
            };

            sessionCookie.Value = Guid.NewGuid().ToString();
        }
        else
        {
            sessionCookie.Expires = DateTime.Now.AddMinutes(30);
        }

        Response.Cookies.Add(sessionCookie);

        base.OnActionExecuted(filterContext);
    }

As this is happening every time a request is made, would this cookie update be noticeable in regards to speed? Any help or suggestions would be greatly appreciated.

\$\endgroup\$
2
\$\begingroup\$

The ideal and correct way is to create a class that inherits ActionFlterAttribute and override OnActionExecuting method. Then register it in the GlobalFilters in Global.asax.cs.

Finally do not use Add but use Set method. Why? Below is from MSDN and explains what the difference is:

The Set method first checks to see if a cookie already exists in the collection and if so updates it. The Set method does not allow duplicate cookies in the cookie collection. To add duplicate cookies in the cookie collection, use the Add method.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.