Source code on GitHub

Blog post on ASP.NET Core MVC Value Provider for Encrypted Route Parameter


Example 1 - All parameters

1. Mark action method with CryptoValueProvider attribute

[CryptoValueProvider]
public IActionResult Example1(int param1, string param2)
{
    ViewBag.param1 = param1;
    ViewBag.param2 = param2;

    return View();
}

2. Create parameter dictionary and encrypt it with CryptoParamsProtector

public class HomeController : Controller
{
    CryptoParamsProtector _protector;

    public HomeController(CryptoParamsProtector protector)
    {
        _protector = protector;
    }

    public IActionResult Index()
    {
        var paramDictionary = new Dictionary();
        paramDictionary.Add("param1", 1234.ToString());
        paramDictionary.Add("param2", "Hello World!");
        ViewBag.encryptedRouteParam1 = _protector.EncryptParamDictionary(paramDictionary);

        return View();
    }
}

3. Use encrypted route parameter to generate link

<a asp-controller="demo" asp-action="example1" asp-route-id="@ViewBag.encryptedRouteParam1"><h4>Example 1 Demo</h4></a>

Example 1 demo


Example 2 - Crypto values combined with visible values

1. Mark only encrypted parameters with FromCrypto attribute

public IActionResult Example2([FromCrypto]int secretPersonId, [FromCrypto]string secretParam2, Person person)
{
    person.PersonId = secretPersonId;
    _repository.UpdatePerson(person);

    ViewBag.secretPersonId = secretPersonId;
    ViewBag.secretParam2 = secretParam2;
    ViewBag.person = person;

    return View();
}

2. Create secret parameter dictionary and encrypt it with CryptoParamsProtector

public class HomeController : Controller
{
    CryptoParamsProtector _protector;

    public HomeController(CryptoParamsProtector protector)
    {
        _protector = protector;
    }

    public IActionResult Index()
    {
        var person = new Person()
        {
            PersonId = 1234,
            FirstName = "Nandip",
            LastName = "Makwana"
        };

        var paramDictionary = new Dictionary();
        paramDictionary.Add("secretPersonId", person.PersonId.ToString());
        paramDictionary.Add("secretParam2", 5678.ToString());
        ViewBag.encryptedRouteParam2 = _protector.EncryptParamDictionary(paramDictionary);

        return View(person);
    }
}

3. Use encrypted route parameter with other request parameter for e.g. HTML form

<form asp-controller="demo" asp-action="example2" asp-route-id="@ViewBag.encryptedRouteParam2" method="post">
    <input asp-for="FirstName" />
    <input asp-for="LastName" />
    <input type="submit" />
</form>

Example 2 demo with HTML form