Set default path=/ when removing cookie

This commit is contained in:
Pavel Krymets 2015-11-13 10:55:16 -08:00
parent cb3e9b1218
commit 690e5a66e5
2 changed files with 47 additions and 30 deletions

View File

@ -80,36 +80,7 @@ namespace Microsoft.AspNet.Http.Internal
/// <param name="key"></param>
public void Delete(string key)
{
var encodedKeyPlusEquals = UrlEncoder.Default.Encode(key) + "=";
Func<string, string, bool> predicate = (value, encKeyPlusEquals) => value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase);
StringValues deleteCookies = $"{encodedKeyPlusEquals}; expires=Thu, 01-Jan-1970 00:00:00 GMT";
var existingValues = Headers[HeaderNames.SetCookie];
if (StringValues.IsNullOrEmpty(existingValues))
{
Headers[HeaderNames.SetCookie] = deleteCookies;
}
else
{
var values = existingValues.ToArray();
var newValues = new List<string>();
for (var i = 0; i < values.Length; i++)
{
if (!predicate(values[i], encodedKeyPlusEquals))
{
newValues.Add(values[i]);
}
}
values = deleteCookies.ToArray();
for (var i = 0; i < values.Length; i++)
{
newValues.Add(values[i]);
}
Headers[HeaderNames.SetCookie] = new StringValues(newValues.ToArray());
}
Delete(key, new CookieOptions() { Path = "/" });
}
/// <summary>

View File

@ -0,0 +1,46 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Xunit;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNet.Http.Internal;
namespace Microsoft.AspNet.Http.Tests
{
public class ResponseCookiesTest
{
[Fact]
public void DeleteCookieShouldSetDefaultPath()
{
var headers = new HeaderDictionary();
var cookies = new ResponseCookies(headers);
var testcookie = "TestCookie";
cookies.Delete(testcookie);
var cookieHeaderValues = headers[HeaderNames.SetCookie];
Assert.Equal(1, cookieHeaderValues.Count);
Assert.StartsWith(testcookie, cookieHeaderValues[0]);
Assert.Contains("path=/", cookieHeaderValues[0]);
Assert.Contains("expires=Thu, 01 Jan 1970 00:00:00 GMT", cookieHeaderValues[0]);
}
[Fact]
public void NoParamsDeleteRemovesCookieCreatedByAdd()
{
var headers = new HeaderDictionary();
var cookies = new ResponseCookies(headers);
var testcookie = "TestCookie";
cookies.Append(testcookie, testcookie);
cookies.Delete(testcookie);
var cookieHeaderValues = headers[HeaderNames.SetCookie];
Assert.Equal(1, cookieHeaderValues.Count);
Assert.StartsWith(testcookie, cookieHeaderValues[0]);
Assert.Contains("path=/", cookieHeaderValues[0]);
Assert.Contains("expires=Thu, 01 Jan 1970 00:00:00 GMT", cookieHeaderValues[0]);
}
}
}