.NET Daily

Issues with Creating Cookies – ASP.NET Core

Introduction

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.


LATEST POSTS

How to solve: An expression tree may not contain a dynamic operation – ASP.NET Core 06th July, 2019

How to use DbContext Scaffold to add only selected tables – ASP.NET Core 01st July, 2019

Microsoft ASP.NET

Issues with Creating Cookies – ASP.NET Core

Posted on .

I have spent quite a few hours in the past two days trying to understand why a very simple block of code for creating a cookie refuses to work in an ASP.NET Core Application.

The code is the following:

public class HomeController : Controller
{
        // GET: /<controller>/
        public IActionResult Index()
        {
            CookieOptions option = new CookieOptions();
            option.Expires = DateTime.Now.AddHours(1);
            option.HttpOnly = false;
            option.Domain = Request.Host.ToUriComponent();
            option.Path = "/";
            HttpContext.Response.Cookies.Append("hello-cookies", "hello-world!", option);
            return View();
 }
}

When this code is executed, everything is fine. No exceptions whatsoever. Still, the cookie was not created in the browser.

I tested this in an ASP.NET Core 2.1 version, then in 2.2, then I tried in every browser I had installed. Even in Postman. Nothing! No Exception, No Cookie.

Later, I have discovered that the damn UseCookiePolicy() middleware that is present in the Startup.cs was blocking the creation of every cookie that I was trying to create.

When I commented that code, everything was fine!

Now, to be honest, that is a great feature to have in an application. However, I didn’t really expect to be that reliable.

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.

There are no comments.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

View Comments (0) ...
Navigation