Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Custom User Defined Headers to be included in Cache #266

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
8 changes: 8 additions & 0 deletions sample/WebApi.OutputCache.V2.Demo/IgnoreController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ public string GetCached()
return DateTime.Now.ToString();
}

//Send the X-Test-Key header with your request and it will cache it based on the value of the X-Test-Key
[CacheOutput(ClientTimeSpan = 50, ServerTimeSpan = 50, IncludeCustomHeaders = "X-Test-Key")]
[Route("cachedwithheaders")]
public string GetCachedWithHeaders()
{
return DateTime.Now.ToString();
}

[IgnoreCacheOutput]
[Route("uncached")]
public string GetUnCached()
Expand Down
25 changes: 23 additions & 2 deletions src/WebApi.OutputCache.V2/CacheOutputAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,9 @@ public override void OnActionExecuting(HttpActionContext actionContext)

var responseMediaType = GetExpectedMediaType(config, actionContext);
actionContext.Request.Properties[CurrentRequestMediaType] = responseMediaType;
var cachekey = cacheKeyGenerator.MakeCacheKey(actionContext, responseMediaType, ExcludeQueryStringFromCacheKey);
var customRequestHeaders = AddCustomRequestHeaders(actionContext);

var cachekey = cacheKeyGenerator.MakeCacheKey(actionContext, responseMediaType, ExcludeQueryStringFromCacheKey, customRequestHeaders);

if (!_webApiCache.Contains(cachekey)) return;

Expand Down Expand Up @@ -254,9 +256,11 @@ public override async Task OnActionExecutedAsync(HttpActionExecutedContext actio
var httpConfig = actionExecutedContext.Request.GetConfiguration();
var config = httpConfig.CacheOutputConfiguration();
var cacheKeyGenerator = config.GetCacheKeyGenerator(actionExecutedContext.Request, CacheKeyGenerator);
var requestHeaders = AddCustomRequestHeaders(actionExecutedContext.Request.Headers);

var responseMediaType = actionExecutedContext.Request.Properties[CurrentRequestMediaType] as MediaTypeHeaderValue ?? GetExpectedMediaType(httpConfig, actionExecutedContext.ActionContext);
var cachekey = cacheKeyGenerator.MakeCacheKey(actionExecutedContext.ActionContext, responseMediaType, ExcludeQueryStringFromCacheKey);
var reqestHeaders = AddCustomRequestHeaders(actionExecutedContext.Request.Headers);
var cachekey = cacheKeyGenerator.MakeCacheKey(actionExecutedContext.ActionContext, responseMediaType, ExcludeQueryStringFromCacheKey, requestHeaders);

if (!string.IsNullOrWhiteSpace(cachekey) && !(_webApiCache.Contains(cachekey)))
{
Expand Down Expand Up @@ -359,6 +363,23 @@ protected virtual void AddCustomCachedHeaders(HttpResponseMessage response, Dict
}
}

protected virtual Dictionary<string, List<string>> AddCustomRequestHeaders(HttpActionContext actionContext)
{
return AddCustomRequestHeaders(actionContext.Request.Headers);
}
protected virtual Dictionary<string, List<string>> AddCustomRequestHeaders(HttpRequestHeaders requestHeaders)
{
Dictionary<string, List<string>> headers = new Dictionary<string, List<string>>();

if (!(string.IsNullOrEmpty(IncludeCustomHeaders)))
{
// convert to dictionary of lists to ensure thread safety if implementation of IEnumerable is changed
headers = requestHeaders.Where(h => IncludeCustomHeaders.ToLower().Contains(h.Key.ToLower()))
.ToDictionary(x => x.Key.ToLower(), x => x.Value.ToList());
}
return headers;
}

protected virtual string CreateEtag(HttpActionExecutedContext actionExecutedContext, string cachekey, CacheTime cacheTime)
{
return Guid.NewGuid().ToString();
Expand Down
35 changes: 33 additions & 2 deletions src/WebApi.OutputCache.V2/DefaultCacheKeyGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ namespace WebApi.OutputCache.V2
{
public class DefaultCacheKeyGenerator : ICacheKeyGenerator
{
public virtual string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
public virtual string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString, Dictionary<string, List<string>> headers)
{
var key = MakeBaseKey(context);
var parameters = FormatParameters(context, excludeQueryString);
string custHeaders = GetCustomHeaders(headers);

return string.Format("{0}{1}:{2}", key, parameters, mediaType);
if (!(string.IsNullOrEmpty(custHeaders)))
return string.Format("{0}{1}:{2}:{3}", key, parameters, custHeaders, mediaType);
else
return string.Format("{0}{1}:{2}", key, parameters, mediaType);
}

protected virtual string MakeBaseKey(HttpActionContext context)
Expand Down Expand Up @@ -57,7 +61,34 @@ protected virtual string FormatParameters(HttpActionContext context, bool exclud
if (parameters == "-") parameters = string.Empty;
return parameters;
}
protected virtual string GetCustomHeaders(Dictionary<string, List<string>> headers)
{
//string returnValue = string.Empty;

if (!(headers == null))
{
//foreach(var item in headers)
//{
// if (!(returnValue.Length > 0))
// {
// //first group and needs to not include the ;
// returnValue = item.ToString();

// }
// else
// {
// returnValue = string.Format("{0}|{1}={2}", returnValue, item.Key, item.Value);
// }
//}
return string.Join("&", headers.Select(x => x.Key.ToLower() + "=" + GetValue(x.Value)));
}
else
{
return string.Empty;
}

//return returnValue;
}
private string GetJsonpCallback(HttpRequestMessage request)
{
var callback = string.Empty;
Expand Down
5 changes: 3 additions & 2 deletions src/WebApi.OutputCache.V2/ICacheKeyGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System.Net.Http.Headers;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Web.Http.Controllers;

namespace WebApi.OutputCache.V2
{
public interface ICacheKeyGenerator
{
string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false);
string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString, Dictionary<string, List<string>> headers);
}
}
11 changes: 8 additions & 3 deletions src/WebApi.OutputCache.V2/PerUserCacheKeyGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
using System.Net.Http.Headers;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Web.Http.Controllers;

namespace WebApi.OutputCache.V2
{
public class PerUserCacheKeyGenerator : DefaultCacheKeyGenerator
{
public override string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
public override string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString, Dictionary<string, List<string>> headers)
{
var baseKey = MakeBaseKey(context);
var parameters = FormatParameters(context, excludeQueryString);
var userIdentity = FormatUserIdentity(context);
string custHeaders = GetCustomHeaders(headers);

return string.Format("{0}{1}:{2}:{3}", baseKey, parameters, userIdentity, mediaType);
if (!(string.IsNullOrEmpty(custHeaders)))
return string.Format("{0}{1}:{2}:{3}:{4}", baseKey, parameters, custHeaders, userIdentity, mediaType);
else
return string.Format("{0}{1}:{2}:{3}", baseKey, parameters, userIdentity, mediaType);
}

protected virtual string FormatUserIdentity(HttpActionContext context)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Web.Http.Controllers;

Expand All @@ -14,6 +15,7 @@ public abstract class CacheKeyGenerationTestsBase<TCacheKeyGenerator> where TCac
private const string ArgumentValue = "val";
protected HttpActionContext context;
protected MediaTypeHeaderValue mediaType;
protected Dictionary<string, List<string>> headers;
protected Uri requestUri;
protected TCacheKeyGenerator cacheKeyGenerator;
protected string BaseCacheKey;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
Expand Down Expand Up @@ -104,6 +105,12 @@ public void custom_unregistered_cache_key_generator_called()
#region Helper classes
private class FailCacheKeyGenerator : ICacheKeyGenerator
{
public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString, Dictionary<string, List<string>> headers)
{
Assert.Fail("This cache key generator should never be invoked");
return "fail";
}

public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
{
Assert.Fail("This cache key generator should never be invoked");
Expand All @@ -120,6 +127,11 @@ public InternalRegisteredCacheKeyGenerator(string key)
_key = key;
}

public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString, Dictionary<string, List<string>> headers)
{
return _key;
}

public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
{
return _key;
Expand Down
8 changes: 7 additions & 1 deletion test/WebApi.OutputCache.V2.Tests/CacheKeyGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
Expand All @@ -17,6 +18,11 @@ class CacheKeyGeneratorTests
{
public class CustomCacheKeyGenerator : ICacheKeyGenerator
{
public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString, Dictionary<string, List<string>> headers)
{
return "custom_key";
}

public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
{
return "custom_key";
Expand Down Expand Up @@ -59,7 +65,7 @@ public void init()
public void custom_default_cache_key_generator_called_and_key_used()
{
var client = new HttpClient(_server);
_keyGeneratorA.Setup(k => k.MakeCacheKey(It.IsAny<HttpActionContext>(), It.IsAny<MediaTypeHeaderValue>(), It.IsAny<bool>()))
_keyGeneratorA.Setup(k => k.MakeCacheKey(It.IsAny<HttpActionContext>(), It.IsAny<MediaTypeHeaderValue>(), It.IsAny<bool>(), It.IsAny<Dictionary<string, List<string>>>()))
.Returns("keykeykey")
.Verifiable("Key generator was never called");
// use the samplecontroller to show that no changes are required to existing code
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ protected override DefaultCacheKeyGenerator BuildCacheKeyGenerator()
[Test]
public void NoParametersIncludeQueryString_ShouldReturnBaseKeyAndQueryStringAndMediaTypeConcatenated()
{
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}-{1}:{2}", BaseCacheKey, requestUri.Query.Substring(1), mediaType), cacheKey,
Expand All @@ -24,7 +24,7 @@ public void NoParametersIncludeQueryString_ShouldReturnBaseKeyAndQueryStringAndM
[Test]
public void NoParametersExcludeQueryString_ShouldReturnBaseKeyAndMediaTypeConcatenated()
{
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}:{1}", BaseCacheKey, mediaType), cacheKey,
Expand All @@ -35,7 +35,7 @@ public void NoParametersExcludeQueryString_ShouldReturnBaseKeyAndMediaTypeConcat
public void WithParametersIncludeQueryString_ShouldReturnBaseKeyAndArgumentsAndQueryStringAndMediaTypeConcatenated()
{
AddActionArgumentsToContext();
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}-{1}&{2}:{3}", BaseCacheKey, FormatActionArgumentsForKeyAssertion(), requestUri.Query.Substring(1), mediaType), cacheKey,
Expand All @@ -46,7 +46,7 @@ public void WithParametersIncludeQueryString_ShouldReturnBaseKeyAndArgumentsAndQ
public void WithParametersExcludeQueryString_ShouldReturnBaseKeyAndArgumentsAndMediaTypeConcatenated()
{
AddActionArgumentsToContext();
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}-{1}:{2}", BaseCacheKey, FormatActionArgumentsForKeyAssertion(), mediaType), cacheKey,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ private string FormatUserIdentityForAssertion()
[Test]
public void NoParametersIncludeQueryString_ShouldReturnBaseKeyAndQueryStringAndUserIdentityAndMediaTypeConcatenated()
{
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}-{1}:{2}:{3}", BaseCacheKey, requestUri.Query.Substring(1), FormatUserIdentityForAssertion(), mediaType), cacheKey,
Expand All @@ -39,7 +39,7 @@ public void NoParametersIncludeQueryString_ShouldReturnBaseKeyAndQueryStringAndU
[Test]
public void NoParametersExcludeQueryString_ShouldReturnBaseKeyAndUserIdentityAndMediaTypeConcatenated()
{
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}:{1}:{2}", BaseCacheKey, FormatUserIdentityForAssertion(), mediaType), cacheKey,
Expand All @@ -50,7 +50,7 @@ public void NoParametersExcludeQueryString_ShouldReturnBaseKeyAndUserIdentityAnd
public void WithParametersIncludeQueryString_ShouldReturnBaseKeyAndArgumentsAndQueryStringAndUserIdentityAndMediaTypeConcatenated()
{
AddActionArgumentsToContext();
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, false, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}-{1}&{2}:{3}:{4}", BaseCacheKey, FormatActionArgumentsForKeyAssertion(), requestUri.Query.Substring(1), FormatUserIdentityForAssertion(), mediaType), cacheKey,
Expand All @@ -61,7 +61,7 @@ public void WithParametersIncludeQueryString_ShouldReturnBaseKeyAndArgumentsAndQ
public void WithParametersExcludeQueryString_ShouldReturnBaseKeyAndArgumentsAndUserIdentityAndMediaTypeConcatenated()
{
AddActionArgumentsToContext();
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true);
var cacheKey = cacheKeyGenerator.MakeCacheKey(context, mediaType, true, headers);

AssertCacheKeysBasicFormat(cacheKey);
Assert.AreEqual(String.Format("{0}-{1}:{2}:{3}", BaseCacheKey, FormatActionArgumentsForKeyAssertion(), FormatUserIdentityForAssertion(), mediaType), cacheKey,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net.Http.Headers;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;

Expand All @@ -8,6 +9,11 @@ public class CacheKeyController : ApiController
{
private class UnregisteredCacheKeyGenerator : ICacheKeyGenerator
{
public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString, Dictionary<string, List<string>> headers)
{
return "unregistered";
}

public string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
{
return "unregistered";
Expand Down