Skip to main content

Set Cookies from a Sitecore Rule Action

Here's a quick one to correct an omission from my previous post where I detailed 3 rule conditions that respond to the presence of a cookie. On reflection I realised I should have included a corresponding action class. So here it is. As before, I haven't spent much time considering the practical applications. I'll leave that part up to you.




Text field: 
Set [CookieName,,,specific cookie] value to [CookieValue,,,specific value] with an expiry of [CookieExpiry,PositiveInteger,defaultValue=&validation=%5E%5C-%7B0%2C1%7D%5Cd%2B(.%5Cd%2B)%7B0%2C1%7D%24&validationText=Please enter a valid number.,specific value] days
public class SetCookieAction : Sitecore.Rules.Actions.RuleAction 
    where T : Sitecore.Rules.RuleContext
{
    public String CookieName { get; set; }
    public String CookieValue { get; set; }
    public String CookieExpiry { get; set; }

    public override void Apply(T ruleContext)
    {
        Assert.IsNotNull(HttpContext.Current, "HttpContext.Current");
        Assert.IsNotNull(CookieName, "CookieName");
        Assert.IsNotNull(CookieValue, "CookieValue");
        Assert.IsNotNull(CookieExpiry, "CookieExpiry");
            
        Double expiry;
        Double.TryParse(CookieExpiry, out expiry);

        var response = HttpContext.Current.Response;
        response.Cookies[CookieName].Value = CookieValue;
        response.Cookies[CookieName].Expires = DateTime.Now.AddDays(expiry);
    }
}

Comments