Click here to Skip to main content
15,672,088 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a website where I created a custom cookie and I am trying to read the cookie value inside my Custom Rewrite Provider running in IIS
Question in short: How to decrypt the cookie inside custom URL rewrite provider?
Below is the code for creating custom cookie
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

        string encryptedTicket = FormsAuthentication.Encrypt(ticket);
        HttpCookie fCookie = new HttpCookie("customCookie", encryptedTicket);
        fCookie.Expires = DateTime.Now.AddDays(7);
        fCookie.Path = "/";

Below code is to read the cookie value inside my Custom Rewrite Provider running in IIS

public class ParseUserNameProvider : IRewriteProvider, IProviderDescriptor
    public IEnumerable<SettingDescriptor> GetSettings()
        throw new NotImplementedException();

    public void Initialize(IDictionary<string, string> settings, IRewriteContext rewriteContext)

    public string Rewrite(string value)
        string[] val = value.Split('=');
        string name = "";
        if (val != null)
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(val[1]);
                name = authTicket.Name;
        return name;

I am getting a error as shown below
Unable to validate data.
      at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(
      Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start,
      Int32 length, IVType ivType, Boolean useValidationSymAlgo,
      Boolean signData)
Updated 13-Jan-16 17:36pm
suhel_khan 14-Jan-16 0:24am    
The basic reason of this is the difference of key while encrypting and decrypting the viewstate data. Suppose an rendered a page with key1 and saved the page state in view state, meanwhile’s key is changed to key2, now when some server side event will occur on page the viewstate will get decrypted and this error will occur as the old view state is now not valid due to a different encryption key.

It may occur when you open a page for along time and after that do some events on that.

Solution Fix the key in your web.config file, so that only one key is used to encrypt and decrypt the viewstate data.
Deepak Rao Kumpala 14-Jan-16 0:36am    
Your solution helps if cookies are sharing between websites, but I am trying to access it inside class library which is deployed to GAC and used as rewrite provider in a IIS.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900