Why do I have a loop in my for cycle?

1

I have a method ActionResult which has a cycle for where I go through all the cookies to eliminate them when doing logout. The problem is that when I call the method from my view (This through a form ) I enter the method but I never finish leaving the cycle for esoy in a loop and I do not know why. The counter at the time of entering tells me that there are x cookies but at the time of going through them I will add one more to the counter of for and never dread never leaving.

My code:

[HttpPost]
[ValidateAntiForgeryToken]
[Route("account/exit")]
public RedirectResult LogOff()
{
    for (int i = 0; i < Request.Cookies.Count; i++)
    {
        var cookie = new HttpCookie(HttpContext.Request.Cookies[i].Name);
        cookie.Expires = DateTime.Now.AddDays(-1);
        cookie.Value = string.Empty;
        Response.Cookies.Add(cookie);
    }

    Session.Abandon();

    return Redirect("miurl");
}

From my view I have the following:

@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
    {
    @Html.AntiForgeryToken()
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Cerrar sesión</a></li>
    }
    
asked by vcasas 15.06.2018 в 16:15
source

1 answer

2

This I have not tried, but you can try to take the names of the cookies before deleting them:

var cookieNames = Request.Cookies.AllKeys.ToList();

Then clear the collection of cookies:

Response.Cookies.Clear();
Request.Cookies.Clear(); // En caso de...

And finally add the cookies:

foreach (var cookieName in cookieNames) {
    Response.Cookies.Add(new HttpCookie { 
        Name = cookieName,
        Value = string.Empty,
        Expires = DateTime.Now.AddDays(-1),
    });
}

Your method would look like this:

[HttpPost]
[ValidateAntiForgeryToken]
[Route("account/exit")]
public RedirectResult LogOff()
{
    // Obtenemos los nombres. 
    var cookieNames = Request.Cookies.AllKeys.ToList();

    // Limpiamos las listas.
    Response.Cookies.Clear();
    Request.Cookies.Clear(); // En caso de...

    // Re-agregamos las cookies con los nuevos valores.
    foreach (var cookieName in cookieNames)
    {
        Response.Cookies.Add(new HttpCookie { 
            Name = cookieName,
            Value = string.Empty,
            Expires = DateTime.Now.AddDays(-1),
        });
    }

    // Terminamos.
    Session.Abandon();
    return Redirect("miurl");
}

That should work (Based on this link), although you would prefer to edit the cookies directly in Response.Cookies :

foreach (var cookieName in Response.Cookies.AllKeys) 
{
    Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(-1);
    Response.Cookies[cookieName].Value = string.Empty;
}

With that another should be enough to adjust the server's response.

    
answered by 15.06.2018 в 16:35