Search code examples
c#asp.net-mvcasp.net-corerazor-pages

how to set cookies in _layout


When the site starts then I have a function that checks if there are user cookies-

        foreach (var cookie in HttpContextAccessor.HttpContext.Request.Cookies)
    {
        if (cookie.Key == "OrderLoginDetails")
        {

            Customer.Cookie = cookie.Value;
        }
    }

And it works great!

The problem starts when I try to make new cookies ...

How can I make new cookies in the Layout file?

I tried like this-

 if (Customer.Cookie == null)
    {
        var newCust = Customer.newCustomer();
        var cookieOptions = new CookieOptions
        {
            Path = "/",
            HttpOnly = false,
            IsEssential = true, //<- there
            Expires = DateTime.Now.AddMonths(1),
        };
        Response.Cookies.Append("OrderLoginDetails", Customer.CustomerCode + Customer.CustomerMail, cookieOptions);


    }

But it does not work.

Best regards


Solution

  • If the code is in a Layout or other Razor view file, you use the Context property to access the HttpContext e.g.

    foreach (var cookie in Context.Request.Cookies)
    {
        if (cookie.Key == "OrderLoginDetails")
        {
            Customer.Cookie = cookie.Value;
        }
    }
    

    And

    Context.Response.Cookies.Append("OrderLoginDetails", Customer.CustomerCode + Customer.CustomerMail, cookieOptions);
    

    Although if you want to execute this code for each page request, you might consider a Filter rather than embedding it in a layout page: https://www.learnrazorpages.com/razor-pages/filters