Skip to content

Instantly share code, notes, and snippets.

@electricessence
Last active March 9, 2018 21:54
Show Gist options
  • Select an option

  • Save electricessence/d435301a02c8b6b7bce70da20de22704 to your computer and use it in GitHub Desktop.

Select an option

Save electricessence/d435301a02c8b6b7bce70da20de22704 to your computer and use it in GitHub Desktop.
public override String GetVaryByCustomString(HttpContext context, String args)
{
//context.Items["VaryByCustom"] = args;
args = args?.Trim(';');
if (string.IsNullOrWhiteSpace(args)) return string.Empty;
return String.Join(';', args.Split(';').Select(a => VaryByCustomStringOptionSingle(context, a)).ToArray());
}
private static readonly Regex KeyWithParams = new Regex(@"(?<Key>.+)(?:\[(?<Param>[^\[]+)\])?", RegexOptions.RightToLeft);
private String VaryByCustomStringOptionSingle(HttpContext context, String arg)
{
Match result = KeyWithParams.Match(arg);
var keyM = result.Groups["Key"];
var paramM = result.Groups["Param"];
var key = keyM.Value;
var param = paramM.Value;
var hasParam = !String.IsNullOrWhiteSpace(param);
switch (key)
{
case "HttpMethod":
return "HttpMethod="+Request.HttpMethod;
case "Locale":
return "Locale="+context.Request.Headers["Accept-Language"]; // Request.UserLanguages
case "IsAuthenticated":
return "IsAuthenticated=" + context.Request.IsAuthenticated;
case "IsSecureConnection":
return "IsSecureConnection=" + Request.IsSecureConnection;
case "Roles":
if(context.Request.IsAuthenticated)
{
string[] roles = RolesCache.GetRolesForUser();
if(roles!=null && roles.Length!=0)
return "Roles=" + roles.Join(',');
}
return "Roles=none";
case "UserNegatedId":
if (context.Request.QueryString.IsBlank(hasParam ? param : "id") && context.User != null && context.User.Identity!=null)
return "UserName=" + context.User.Identity.Name;
return "UserNegatedId";
case "AbsolutePath":
return "AbsolutePath=" + context.Request.Url.AbsolutePath;
case "AbsoluteFolderPath":
string ap = context.Request.Url.AbsolutePath;
int lastSlash = ap.LastIndexOf("/", StringComparison.Ordinal);
return "AbsoluteFolderPath=" + (lastSlash<0 ? "/" : ap.Substring(0, lastSlash) );
case "Param":
if (hasParam)
return key + "=" + (context.Request.Params[param] ?? String.Empty);
break;
}
return base.GetVaryByCustomString(context, arg);
}
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Request.Form.Count != 0) Response.Cache.SetNoServerCaching();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment