Site icon port135.com

Best practices for session state and cookies in ASP.NET application

Session state best practices:

Cookie best practices:

.
Code examples

In order to implement best practices for cookies, add the code lines below into your application.

Web.config file:

<system.web>
<sessionState regenerateExpiredSessionId="false" cookieless="UseCookies" cookieName="id" />
</system.web>

Code-behind file:

Response.Cookies.Add(new HttpCookie("id", ""));
Response.Cookies["id"].HttpOnly = true;
Response.Cookies["id"].Secure = Convert.ToBoolean(ConfigurationManager.AppSettings["SecureCookie"]);

References:

Is your application is generating a new session ID after postbacks? Check this out for instructions to solve this issue: Solved: ASP.NET application generates a new session ID after every postbacks

Bonus: How to avoid using the same Session ID

Especially for the high CPU usage issues, you may come across the error message below in DebugDiag reports:

Multiple requests in the process state with the same ASP.NET Session ID were detected in the dump file. At any point of time, ASP.NET executes only one request with the same session id and the remaining requests are queued behind the request which is getting executed.

There are a few recommendations about avoiding using the same session ID for multiple requests OR reducing the delays when there are multiple requests with the same session ID:

  1. Try not use session variables. Try to use cookies or database tables instead. For example: Instead of storing the user preferences in the session, you can store them in a cookie. Another example: You can store the currently logged in user in cache or database if form authentication class doesn’t have this information
  2. If you have to use session variables:
    1. Try to use ReadOnly value for EnableSessionState where possible. This will not block other Read requests. If you assign True to this parameter, it will block both Read and Write requests.
    2. Make sure the requests are not long running so that if there is a lock on the session variable, it won’t delay other requests for a long time
    3. You can try decreasing the value of LOCKED_ITEM_POLLING_INTERVAL. This is 500 ms by default which means the session will be checked if it is free every 500 ms. Decreasing it may reduce the delays for pending requests but it may increase CPU overload. I would recommend being extra cautious and doing extra tests if you want to change this interval.

More information: Why can’t I execute two requests from the same session simultaneously for an ASP.NET application?

Exit mobile version