Solved: ASP.NET application generates a new session ID after every postbacks

You need to keep the same session ID for the same visitor in the same connection. If session ID changes in between page redirection, It will probably break your code especially if you are using session ID to improve ViewState complexity such as the example below:

Page.ViewStateUserKey = Session.SessionID;


  1. Make sure you don’t create session cookie repeatedly. If the line that you create session cookie is executed between postbacks, you will end up having a different session ID since the session cookie is recreated.

    Response.Cookies.Add(new HttpCookie("id", ""))
  2. Make sure you don’t generate session ID repeatedly. An example line of session ID creation:

  3. Assign a dummy value to your session cookie in Global.asax (See details here)

    protected void Session_Start(object sender, EventArgs e)
         // It adds an entry to the Session object so the sessionID is kept for the entire session
         Session["init"] = "session start";
  4. Assign a dummy value to your session cookie in Page_Load method of homepage:

    protected void Page_Load(object sender, EventArgs e)
         Session["init"] = "session start";

It’s working in server but not in localhost?

In your web.config file, change the value of httpOnlyCookies and requireSSL parameters to false. If you keep them in true, local server will force application to regenerate session between page redirections. Make sure to switch these values back to true before you migrate your code to the server.

<httpCookies httpOnlyCookies="false" requireSSL="false"/>

How to remove server data from response headers of your ASP.NET application?

The less you give to hackers, the safer your web application is. Hiding the product, technology, and version information of your server is one big step towards narrowing the attack surface of your application.

By default, IIS server will reveal this data to everyone who has access to your application:

Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET

This data can be viewed by a proxy such as Fiddler.

Server details
Server details

You can remove these headers by add a few lines into web.config and Global.asax files. You don’t need to do any configuration changes in IIS if you are using IIS 7 or an upper version.

Remove “Server” header

Add this method into Global.asax:

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)

Add this line into Application_Start in Global.asax:

PreSendRequestHeaders += Application_PreSendRequestHeaders;

Remove “X-AspNet-Version” header

Add this line into web.config:

     <httpRuntime enableVersionHeader="false" />

Remove “X-Powered-By” header

Add this line into web.config:

               <remove name="X-Powered-By" />