Change cookie path

Adeel Mirza 21 Reputation points
2024-06-13T11:23:12.5066667+00:00

In my ASP.NET application, I want to change the cookie path from the root to some specific folder. How can I do that?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,408 questions
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 27,581 Reputation points
    2024-06-13T11:42:47.6566667+00:00

    Is this an IIS virtual path question or are you trying to share or not share a cookie? Anyway, the framework exposes a Path property where the path can be changed.

    ASP.NET Core

    https://learn.microsoft.com/en-us/dotnet/api/system.net.cookie.path?view=net-8.0

    ASP.NET

    https://learn.microsoft.com/en-us/dotnet/api/system.net.cookie.path?view=netframework-4.8.1

    0 comments No comments

  2. SurferOnWww 2,411 Reputation points
    2024-06-14T01:26:31.65+00:00

    How can I do that?

    See "Limiting Cookies to a Folder or Application" section in the following Microsoft document:

    ASP.NET Cookies Overview

    Can you tell us the purpose? I am wondering why you need to specify the path since the default setting ("/") is usually practical in ASP.NET Web app.

    Do you understand that there is limitation as described in the above Microsoft document? Do you realize that you will have to specify the path every time you modify or delete the cookie and it might be very cumbersome?

    0 comments No comments

  3. Lan Huang-MSFT 28,831 Reputation points Microsoft Vendor
    2024-06-14T09:20:19.8766667+00:00

    Hi @Adeel Mirza,

    You can try to create your own SessionIDManager, but you will also need to configure it on Web.config.

    Your SessionIdManager class,

    public class MySessionIDManager : SessionIDManager, ISessionIDManager
    {
        void ISessionIDManager.SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
        {
            base.SaveSessionID(context, id, out redirected, out cookieAdded);
    
            if (cookieAdded)
            {
                var name = "ASP.NET_SessionId";
                var cookie = context.Response.Cookies[name];
                cookie.Path = "/yourPath";
            }
        }
    }
    

    Web.config, replace namespace and class for yours. This goes inside <system.web> section.

    <sessionState sessionIDManagerType = "Namespace.MySessionIDManager"></sessionState>
    

    ASP.NET Forum - Explains how to override path

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments