How to Add Cookies to the Http Response in AspNet 6 MVC

Question: How do you add a cookie to an HttpContext Response in C# MVC AspNet 6?


Please Login to see the rest of the answer

Answer: If you have been trying and failing to add a Cookie to the HttpContext Response you might have been trying to add the Cookie from a Respository Class or a Service Class. Remember the Response is served from the Controller in MVC archtecture, therefore the best place to add a cookie to the Http Response is in the Controller.

Here is how you add a cookie to the HttpContext Response

           CookieOptions option = new()
            {
                MaxAge = TimeSpan.FromDays(7),
                Secure = true
            };

            _httpContext.HttpContext.Response.Cookies.Append("NameHere", "ValueHere", option);

After appending the cookie to the response verify in your browser that infact the cookie is getting dropped. Checking for cookes on the Server side had an overhead, remember you want to get the user out quickly so they can have their response. However, you could utilize the Async Await methodology to check for cookies then carry on with the operation, but you cannot hold the Request Serving because you need to validate the cookie, unless if the cookie is critical to the application operations.

- Hope this helps


Write an Article
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.


© 2022 - ErnesTech - Privacy