---
title: "How to create a Cookie in C#, which is both side modifiable."  
description: "How to create a Cookie in C#, which is both side modifiable."  
author: "Ravi Vishwakarma"  
published: 2025-05-05  
updated: 2025-05-21  
canonical: https://www.mindstick.com/forum/161568/how-to-create-a-cookie-in-c-sharp-which-is-both-side-modifiable  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# How to create a Cookie in C#, which is both side modifiable.

How to create a [Cookie](https://www.mindstick.com/blog/123/what-is-cookie-poisoning) in C#, which is both side modifiable.

## Replies

### Reply by Utpal Vishwas

In C#, you can create a **cookie that is modifiable from both the client-side (JavaScript) and server-side (C#)** by ensuring the cookie meets these two criteria:

### Key Requirements

- `HttpOnly = false` — so JavaScript can read/modify it.
- **No** `Secure` **flag** (unless using HTTPS).
- **Accessible Path** — set `Path = "/"` if you want it globally accessible.

## 1. Set a Modifiable Cookie in C# (Server-Side)

In **ASP.NET MVC or WebForms**, you can use:

```cs
HttpCookie cookie = new HttpCookie("user-preference", "dark-mode");
cookie.Expires = DateTime.Now.AddDays(7);     // Optional: persist cookie
cookie.HttpOnly = false;                      // Required to allow JavaScript access
cookie.Path = "/";                            // Available site-wide

Response.Cookies.Add(cookie);
```

In **ASP.NET Core**:

```cs
Response.Cookies.Append("user-preference", "dark-mode", new CookieOptions
{
    Expires = DateTimeOffset.Now.AddDays(7),
    HttpOnly = false,
    Path = "/"
});
```

## 2. Access and Modify the Cookie via JavaScript (Client-Side)

```javascript
// Read cookie
function getCookie(name) {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  return match ? decodeURIComponent(match[2]) : null;
}

// Set or update cookie
document.cookie = "user-preference=light-mode; path=/; max-age=604800"; // 7 days
```

> `document.cookie` can only access cookies that are **not** `HttpOnly` and within the current path/domain.

## 3. Modify the Cookie in C# Again (Optional)

```cs
if (Request.Cookies["user-preference"] != null)
{
    var cookie = new HttpCookie("user-preference", "updated-mode");
    cookie.Expires = DateTime.Now.AddDays(7);
    cookie.HttpOnly = false;
    Response.Cookies.Set(cookie);
}
```

## Important Notes

1. Avoid storing **sensitive data** (like tokens, user IDs) in client-accessible cookies.
2. Cookies sent by the browser will always be the **latest set value**, whether it was updated client- or server-side.
3. Cookies are limited in size (~4 KB per cookie).


---

Original Source: https://www.mindstick.com/forum/161568/how-to-create-a-cookie-in-c-sharp-which-is-both-side-modifiable

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
