Check if cookies exist in ASPNET CORE

Asked

Viewed 277 times

2

I’m migrating from the Asp.net Webforms to the Core 2.2 and in the application, we stored information such as Id, and other parameters. In Asp.Net Core I use Seguinte Iactionresult to record the cookie:

public IActionResult GravaCookie(string setting, string settingValue, bool isPersistent)
    {
        if (isPersistent)
        {
            CookieOptions options = new CookieOptions();
            options.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Append(setting, settingValue, options);
        }
        else
        {
            Response.Cookies.Append(setting, settingValue);
        }
        ViewBag.Message = "Cookie Armazenado!!!";
        return View("Index");
    }

To retrieve it I use the following code:

ViewBag.FontName = Request.Cookies["fontName"];

Through Webforms I checked with the following code:

if (Request.Cookies["EstaAtivo"].Value != null)
{
    Response.Redirect("~/garantido");
}
else
{
    Response.Redirect("~/entrar");
}

How I do the same check by Asp.Net Core?

1 answer

2


Just do like this:

if (!string.IsNullOrEmpty(Request.Cookies["EstaAtivo"]))
{
    Response.Redirect("~/garantido");
}
else
{
    Response.Redirect("~/entrar");
}

because the Request.Cookies["EstaAtivo"] returns a type string.

You can do it this way too:

string EstaAtivo = Request.Cookies["EstaAtivo"];
if (!string.IsNullOrEmpty(EstaAtivo))
{
    Response.Redirect("~/garantido");
}
else
{
    Response.Redirect("~/entrar");
}
  • Interesting, the second way works, the first one has had no effect. Apparently you need to declare the cookie as a string to see if it actually exists!

  • Both ways work @Claudineiferreira ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.