How to add cookie in Acumatica
There are cases when you may need to put some data into cookies.
For example, I faced a problem in Acumatica when I needed to extract a webhook url using JS.
In the case of one tenant, the CompanyID was not contained in the cookie and threw a null reference exception. To solve this, I used the code below. I created a CompanyID in the cookie and assigned it the value.
HttpContext.Current is a property that gives access to the current context of an HTTP request in ASP.NET.
A new HttpCookie object is created with the name CompanyID and value, which is passed as a method parameter.
HttpCookie(“CompanyID”, value) - the constructor of the HttpCookie class takes two parameters: the name of the cookie and its value. In this case, CompanyID is the name of the cookie, and value is a value that contains the company identifier.
The Path = “/” property means that this cookie will be available for all requests to the site (for all subdirectories of the site).
context.Response.Cookies.Add(companyCookie) - The created cookie is added to the cookie collection in the response sent to the client side.
When the browser receives this response, it saves the cookie and will send it back to the server in subsequent requests to that domain.
Cookie expiration date: As it stands, the cookie is a session cookie, meaning it will be deleted when you close the browser. If you want the cookie to last longer, you can add an expiration date:
companyCookie.Expires = DateTime.Now.AddDays(30);
This way you can add the data you need to cookies for your own purposes.