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?


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






© 2024 - ErnesTech - Privacy
E-Commerce Return Policy