.NET, Archive, ASP.NET, C#
     

Cookie Renaming in ASP.NET

In ASP.NET you can seamlessly rename cookies on the fly with the help the PreSendRequestHeaders and BeginRequest events of the HttpApplication class.

Both events call EventArgs delegates, with the sender object as a HttpApplication instance.

     /// 
     /// Called when a cookie is about to be sent to the browser.
     /// 
     private void CookieOut(object sender, EventArgs e) {
         HttpApplication app = (HttpApplication)sender;
         HttpCookie cookie = app.Response.Cookies["ASP.NET_SessionId"];
         if (cookie != null) {
             app.Response.Cookies.Remove("ASP.NET_SessionId");
             cookie.Name = "fooBar";            app.Response.Cookies.Add(cookie);
         }
     }
 
 

The above method will find a cookie of a specific name, and rename it to something else. In this example, everything in ASP.NET that occurs before the HttpApplication.PreSendRequestHeaders is called will refer to the cookie as «ASP.NET_SessionId». By the time the cookie reaches the browser, it is called «fooBar».

This can be useful when you cannot otherwise control the name of a cookie. The above example is only half of the solution. The cookie will need to be renamed again when it returns from the browser.

      /// 
       /// Called when a cookie is coming into the application.
       /// 
       private void CookieIn(object sender, EventArgs e) {
           HttpApplication app = (HttpApplication)sender;
           HttpCookie cookie = app.Request.Cookies["fooBar"];
           if (cookie != null) {
               app.Request.Cookies.Remove("fooBar");
               cookie.Name = "ASP.NET_SessionId";
               app.Request.Cookies.Add(cookie);
           }
       }    

With the help of the HttpAplication.BeginRequest event, the above method will rename the otherwise named «fooBar» cookie to its original name. All events occurring after BeginRequest will refer to the cookie as «ASP.NET_SessionId», and will be unaware of what has just occurred.

The only caveat to the above solution, is that each cookie practically has two names. In the above example, user code will never be able to create a cookie named «fooBar», as it is already used by the cookie named «ASP.NET_SessionId».

About Jason

Джейсон является опытным предпринимателем и разработчиком программного обеспечения, квалифицированным в области лидерства, мобильной разработки, синхронизации данных и архитектуры SaaS. Он получил степень бакалавра наук (B.S.) в области компьютерных наук в Университете штата Арканзас.
View all posts by Jason →

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *