Login Register
Code2night
  • Home
  • Guest Posts
  • Blog Archive
  • Tutorial
  • Languages
    • Angular
    • C
    • c#
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
  1. Home
  2. Blogpost

Url Encryption in Asp.Net MVC

Date- May 04,2021

13072

Free Download Pay & Download
Url Encryption Custom Helpers

Hello and welcome to Code2Night. In this tutorial, we'll look at how to build Url Encryption in Asp.Net MVC. There are a couple of methods that give url encryption but appear to be quite difficult to implement. In this tutorial, we will use simple custom HTML helpers to encrypt URLs.


URL Encryption

Url Encryption in Asp.Net MVC

So, starting from the beginning Url encryption is a really important feature in today's world as it provided protection to the data our website often shares with a query string. So while using query strings and hiding the actual data from the user so that can't change that for misuse we often use url encryption.

Html Helpers

For URL encryption, we actually need to think about two things. Firstly, how to encrypt data in such a way that it can be used globally, and second how to decrypt data in such a way that you don't have to change too many things. So for the encryption of URLs, we can use custom Html Helpers. In the below example, we are creating a helper which will take action, controller, parameter, and HTML class and will return an anchor tag with an encrypted URL.


  public static MvcHtmlString EncodedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes,string iconclass)
        {
           
          
            string queryString = string.Empty;
            string htmlAttributesString = string.Empty;
            if (routeValues != null)
            {
                RouteValueDictionary d = new RouteValueDictionary(routeValues);
                for (int i = 0; i < d.Keys.Count; i++)
                {
                    if (i > 0)
                    {
                        queryString += "?";
                    }
                    queryString += d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
                }
            }

            if (htmlAttributes != null)
            {
                RouteValueDictionary d = new RouteValueDictionary(htmlAttributes);
                for (int i = 0; i < d.Keys.Count; i++)
                {
                    htmlAttributesString += " " + d.Keys.ElementAt(i) + "=" +"'"+ d.Values.ElementAt(i)+"'";
                }
            }
           

            //What is Entity Framework??
            StringBuilder ancor = new StringBuilder();
            ancor.Append("<a ");
            if (htmlAttributesString != string.Empty)
            {
                ancor.Append(htmlAttributesString);
            }
            ancor.Append(" href='");
            if (controllerName != string.Empty)
            {
                ancor.Append("/" + controllerName);
            }

            if (actionName != "Index")
            {
                ancor.Append("/" + actionName);
            }
            if (queryString != string.Empty)
            {
                ancor.Append("?q=" + EncryptURL(queryString));
            }
            ancor.Append("'");
            ancor.Append(">");
            if(!string.IsNullOrEmpty(iconclass))
            ancor.Append("<i class='" + iconclass + "'></i> ");
            ancor.Append(linkText);
            ancor.Append("</a>");
            return new MvcHtmlString(ancor.ToString());
        }
        public static string EncryptURL(string clearText)
        {
            string EncryptionKey = "LUPHLAKMAKJ2SPBNI99212";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }

So, you can place this helper inside a static class and use it afterward. EncodedActionLink 

This will be used on view as you can see in the below example

 @Html.EncodedActionLink("Create", "Add", "Master", new { Id=1}, new { @class = "btn btn-primary" }, null)

So, this will return you an anchor tag. When you will click this anchor your page will redirect with encrypted data which you have passed to the helper. However, the controller and action will be the same just the query string will be encrypted.


The decryption of Encrypted Url

So, after encryption, we have to create a global method for the decryption of the URL. We will create a custom filter attribute for this purpose.

      
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class EncryptedActionParameterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
           
            Dictionary<string, object> decryptedParameters = new Dictionary<string, object>();
            if (HttpContext.Current.Request.QueryString.Get("q") != null)
            {
                string encryptedQueryString = HttpContext.Current.Request.QueryString.Get("q");
                string decrptedString = Decrypt(encryptedQueryString.ToString());
                string[] paramsArrs = decrptedString.Split('?');

                for (int i = 0; i < paramsArrs.Length; i++)
                {
                    string[] paramArr = paramsArrs[i].Split('=');
                    //if(paramArr[1].GetType().Name == "String")
                    //    decryptedParameters.Add(paramArr[0], paramArr[1]);
                    //else
                    int val = 0;
                    if(Int32.TryParse(paramArr[1],out val))
                        decryptedParameters.Add(paramArr[0], Convert.ToInt32(paramArr[1]));
                    else
                        decryptedParameters.Add(paramArr[0], paramArr[1]);
                }
            }
            for (int i = 0; i < decryptedParameters.Count; i++)
            {
                filterContext.ActionParameters[decryptedParameters.Keys.ElementAt(i)] = decryptedParameters.Values.ElementAt(i);
            }
            base.OnActionExecuting(filterContext);

        }
        
        private string Decrypt(string cipherText)
        {
            string EncryptionKey = "JUDHAAUMAKV2SPBNI99212";
            cipherText = cipherText.Replace(" ", "+");
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
       
    }

So, you can use this custom filter attribute. This will decrypt the query string and will pass the original data in the action parameters. Let's have a look at how to use this.


   [EncryptedActionParameter]
        public ActionResult Create(int Id)
        { return View();}

So, [EncryptedActionParameter], is the same custom filter attribute that we have created in the last step. You have to use this attribute wherever you want to decrypt the encrypted data. And you can get original data in your parameters. 

This is how your URL will look after encryption, but it will give correct data in your action parameters. So this is how you can implement URL encryption in Asp.Net MVC.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

How to generate pdf using itextsharp in asp.net mvc
Aug 06, 2023
How to implement JWT Token Authentication and Validate JWT Token in ASP.NET MVC using JWT
Oct 12, 2022
Import Excel in Asp.net MVC using OLE DB
Jun 23, 2022
Integrating Google Sign in Asp.net MVC
Jan 22, 2022

Comments

Contents

More in ASP.NET MVC

  • Implement Stripe Payment Gateway In ASP.NET 58601 views
  • Jquery Full Calender Integrated With ASP.NET 39506 views
  • Microsoft Outlook Add Appointment and Get Appointment using … 27406 views
  • Payumoney Integration With Asp.Net MVC 23090 views
  • MVC Crud Operation with Interfaces and Repository Pattern wi… 21784 views
View all ASP.NET MVC posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • C
  • c#
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page