Does Session use cookies in Asp.Net?

It’s very confusing for many developers that session use cookies or not, and also a interesting interview question for .net developer ūüôā Let’s understand the relation between session and cookies-

Does session use cookies? Answer is- YES and NO.

One more confusion?

While using session in the application we have two things which are SessionID which is used to uniquely identify the session variables and Session Value which is the actual data stored in the session variables.

As session is a server side and cookies are client side state management techniques, so session actual data always stored on the server memory by default. The following list describes the available session storage modes-

  • InProc¬†mode,¬†which stores session state in memory on the Web server. This is the default.
  • StateServer¬†mode,¬†which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer¬†mode¬†stores session state in a SQL¬†Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom¬†mode, which enables you to specify a custom storage provider.
  • Off¬†mode,¬†which disables session state.

I hope it’s clear that session data is stored on the server and has no relationship with the cookies.

Now let’s understand the session keys storage types-





Session and cookies relationship are limited to only session keys not session value.


Session¬†use¬†cookies¬†‚ÄstYes¬†: ¬†By default¬†Session key is stored in an HTTP ¬†non-persistent cookie that the client sends to the server (and server to client)¬†on each request/responses.¬†The server can then read the key from the cookie and re-inflate the server session state.

If we will try to run below code after disabled the cookies then it will not work that proves that session use the cookies.

Session¬†use¬†cookies¬†‚ÄstNo¬†: There is the possibility that¬†browser does not support cookie or disabled, then can not create a cookie to store session keys.¬†ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session keys not in a cookie, but in the URLs. This can be done by setting cookieless=‚ÄĚtrue‚ÄĚ in the web.config file ¬†as-

<sessionstate cookieless=‚ÄĚtrue‚ÄĚ />



Programming is Easy…

What is Cookies in .Net?

Cookies are used to store data at client side. It can be used to store user name on login form or in the shopping site to store cart items etc…

There are two type of cookies-

  • Persistent cookies–  This type of cookies value does not lost even after close the browser window. Values are stored at client side until its expiration date. To create the persistent cookies just set the cookies expiration date like 1 day, 2 day etc..
  • Non Persistent cookies – This type of cookies values lost after close the browser window. To create this type of cookies do not add the expiration date.

To delete the existing cookies just set the cookies expiration date to any past date.

Cookies are created via the Response.Cookies object and can  be read using Request.Cookies object. Cookies can be created to store single value and multiple value.  Benefit of creating the multi value cookies is that we do not need to set the expiration date for each.

Bootstrap .woff2 fonts not getting loaded correctly ?

If you are also facing the issue of not loading bootstarp .woff2 fonts and getting errors in browser console window. Then this article may be useful for you.

It happens due to the server’s not configured for¬†MIME type ‘woff’ or ‘woff2’. We can easily fix this issue by just adding MIME type to the server either using IIS manager or web.config file.

Using IIS Manager-

  1. open IIS manager
  2. Features View -> MIME Types
  3. Actions -> Add
  4. You will see add MIME Type box and put woff2 extension in the file extension “.woff2”
  5. and MIME type as “application/font-woff2” as well.

Using web.config file-

		<remove fileExtension=".woff2" />
		<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />

Programming is Easy…

How to add a Favicon to your website?

A Favicon is that which browsers displays next to page’s title, or in the address bar next to its URL or in the list of bookmarks.


Some web services and search engines (such as DuckDuckGo) also use the favicon-


So the favicon is pretty important like site recognition in the browser and expand your site’s branding. The desired favicon size is 16X16 and should be in the .ico file format. We can create favicon using any online tool with the image what we want to display in the our site favicon places. Ex-

Step 1:-Go to

Step 2:-Browse for the respective image for your website ,that would become your website’s brand.

Step 3:-Generate the favicon and download the favicon and add it in your root directory(Sometimes it doesnot refreshes itself so please clear your browser cache).

Step 4:-

<link rel="shortcut icon" href="/NAME of your FAVICON.ico" type="image/x-icon">

Put the above code in the <head>…….</head> section of your webpages.

Programming is Easy…

How to disable the button and change text to processing while the page is processing?

As we know that a button behaviour is submitting the data, If we click multiple times on a button then form data submits multiple times and makes repetitive entries in the database which is wrong. To prevent multiple entry we can follow the following simple solution.

1) On very first click we will disabled the button using any client side scripting language.

2) we can also change the text like “Processing…” etc… if needed.

3) On completion the task we will enable the button and change the text to old one.

function DisableButton() {
    $("#btnSubmit").attr("disabled", "disabled");
    $("#btnSubmit").attr('value', 'Processing...');

//We will call this method on client side using onClientClick event.  
<asp:Button runat="server" ID="btnSubmit" ClientIDMode="Static" 
Text="Submit" OnClick="btnSubmit_Click"  OnClientClick="DisableButton();" />

Here button will cause the page postback so the button will get the enabled and the text will change the same as before. If your button does not cause the page postback then we need to enable the button on the task completion in our scripting code.

function EnableButton() {
    $("#btnSubmit").attr('value', 'submit');

Programming is Easy..

How to prevent embedding web page inside an iframe?

If you¬†don’t want to embed your web sites/pages into another sites then “X-Frame-Options”¬† response header is the easiest way to do this.

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object> . Web sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

There are three possible values for X-Frame-Options:

1) DENY :- The page cannot be displayed in a frame.

2) SAMEORIGIN :- The page can only be displayed in a frame on the same origin as the page itself.

3) ALLOW-FROM :- The page can only be displayed in a frame on the specified origin.

Configuring IIS :-


      <add name="X-Frame-Options" value="SAMEORIGIN" />


When an attempt is made to load content into a frame, and permission is denied by the X-Frame-Options header, Firefox currently renders about:blank into the frame. At some point, an error message of some kind will be displayed in the frame instead.

References :-

Programming Is Easy…

Web Applications Performance Optimization ‚Äď 20 Best Practices

Following are the some ‚Äúbest practices‚ÄĚ to enhance the performance of web applications:-

Optimizing Images:-

  • Resize: Check whether the pallet size for images is optimal and convert them to PNG format.
  • CSS Sprites: Rearrange the images and combine similar colors for a smaller file size.
  • Keep Favicon.ico small and cacheable:¬† This process can help in optimizing the rendering speed. It is also suggested to keep the size under 1kb and set expiry header.
  • Use only what you need: be mindful of scaling the images in HTML and using bigger images than absolutely required.

Optimizing CSS:-

  • Style sheets to be at the top: By placing style sheets at the top within the head document, users can let the pages to render in a progressive manner.
  • Avoid choosing @import: it‚Äôs important to choose <link> over @import, as @import causes CSS to go to the bottom of the pages in internet explorer.
  • Limit CSS expressions: Use one-time expressions which prevent them from being evaluated repeatedly.
  • Avoid filters: To avoid browser freezes and rendering blocks, consider utilizing degrading PNG8.

Optimizing JavaScript:-

  • Place scripts at the bottom: By using the defer attribute, JavaScript can be forced to the bottom of the page.
  • Remove duplicate scripts: Integrate the script management in the templating system to avoid multiple HTTP requests.
  • Compress JavaScript and CSS: Remove unnecessary code and characters from the script and reduce its size.
  • Make CSS and JavaScript external: We suggest employing external files except home pages for browsers caching. Use in-lining for home pages.
  • Develop smart end handlers: Use event delegation methods to avoid problems of excessive event handlers.
  • Reduce Dom Access: Avoid DOM access with JavaScript to boost page response metrics.

Optimizing Server:-

  • Use Content delivery network: Using a content delivery network is generally thought to be among the best ways for improving the performance and speed of websites for end users.
  • Use Gzip compression: Gzip compression can reduce HTTP requests and improve the response time of websites.
  • Early flush buffer: This allows saving browser idle time by flushing within the head.
  • Prevent empty image src:¬† This helps avoid server requests from the browser.
  • Use ‚Äėexpires‚Äô and ‚Äėcache control‚Äô: We suggest the use of the never expire method for static components of the website and for dynamic content the cache control header.
  • Cloud methodology: Cloud computing can play a key role in bumping up the performance of a website. The abundant resources of the Cloud can be a Godsend for resource hungry websites. In addition the ‚Äúmanaged‚ÄĚ services from most Cloud providers can be of added assistance when it comes to website performance optimization.

References :-


Programming is Easy…

ASP.NET – Page life cycle – Part-2

Below are the General Page Life-cycle Stages :-

Some parts of the life cycle occur only when a page is processed as a postback. For postbacks, the page life cycle is the same during a partial-page postback (as when you use an UpdatePanel control) as it is during a full-page postback.

Page request :-

The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled , or whether a cached version of the page can be sent in response without running the page.


In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

Initialization :- 

During page initialization, controls on the page are available and each control’s¬†UniqueID¬†property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load :-  

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling :- 

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValidproperty of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)

Rendering :- 

Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the¬†Render¬†method for each control, providing a text writer that writes its output to the¬†OutputStream¬†object of the page’s¬†Response¬†property.

Unload :- 

The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such asResponse and Request are unloaded and cleanup is performed.


Life Cycle Events :- 

Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.

PreInit :- 

Raised after the start stage is complete and before the initialization stage begins. Use this event for the following:

1) Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
2) Create or re-create dynamic controls.
3) Set a master page dynamically.
4) Set the Theme property dynamically.
5) Read or set profile property values.

Init :-  

Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Initevent of the page.

Use this event to read or initialize control properties.

InitComplete :- 

Raised at the end of the page’s initialization stage. Only one operation takes place between the¬†Init¬†and¬†InitComplete¬†events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the¬†ViewState¬†collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their¬†Init¬†event.

Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad :- 

Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load :- 

The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.

Use the OnLoad event method to set properties in controls and to establish database connections.

Control events : –

Use these events to handle specific control events, such as a¬†Button¬†control’s¬†Click¬†event or ¬†¬†TextBox¬†control’s¬†TextChanged¬†event.

LoadComplete :- 

Raised at the end of the event-handling stage.

Use this event for tasks that require that all other controls on the page be loaded.

PreRender :- 

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete :- 

Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.


Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.


This is not an event; instead, at this stage of processing, the¬†Page¬†object calls this method on each control. All ASP.NET Web server controls have aRender¬†method that writes out the control’s markup to send to the browser.

If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the¬†Render¬†method. For more information, seeDeveloping Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.


Raised for each control and then for the page.

In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.


References :-


Programming is Easy….

ASP.NET – Page life cycle – Part-1

Following are the steps which occur when we request a ASPX page :-
The browser sends the request to the webserver (IIS). Once IIS receives the request he looks on which engine can serve this request. Engine means the DLL who can parse this page or compile and send a response back to browser. Which request to map to is decided by file extension of the page requested.

Depending on file extension following are some mapping:-
1 .aspx, for ASP.NET Web pages,
2 .asmx, for ASP.NET Web services,
3 .config, for ASP.NET configuration files,
4 .ashx, for custom ASP.NET HTTP handlers,
5 .rem, for remoting resources

Once IIS passes the request to ASP.NET engine, page has to go through two section HTTP module section and HTTP handler
section.  Both these section have there own work to be done in order that the page is properly compiled and sent to the IIS.

HTTP modules inspect the incoming request and depending on that, they can change the internal workflow of the request.

HTTP handler actually compiles the page and generates output.

So now the HTTP handler is where the actual compilation takes place and the output is  generated. Following is a paste from HTTP handler section of WEB.CONFIG file.

<add verb="*" path="*.vjsproj" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.java" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.jsl" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler" />
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
<add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" />

=> Depending on the File extension handler decides which Namespace will generate the output. Example all .ASPX
extension files will be compiled by System.Web.UI.PageHandlerFactory
=> Once the file is compiled it will be send back again to the HTTP modules and from there to IIS and then to the browser.


Continue reading