In this tutorial, you will learn how to get the current Episerver Commerce product or variant object in code from within a non-Episerver controller. There are certain circumstances when working with Episerver Commerce where you might need to come off the beaten track. For example, you need to create a custom ActionFilterAttribute or a vanilla MVC controller. When you find yourself within a non-Episerver controller and you need access to the current object, what do you do? If you find yourself in this situation, read on to learn how to solve this challenge 🔥🔥🔥

Getting EntryContentBase from the HTTP context

The code below assumes that you are working within an ActionFilterAttribute, however, as long as you have access to the controller context the same principles apply to wherever you are in code:

The first approach involves using the data stored in the currentContent property from the RouteData object. After accessing currentContent you can cast the object to type EntryContentBase or your product or variant type. Using EntryContentBase is useful as it will allow you to process products and variants at the same time with the same code 🤔.

Getting the Variant from the HTTP context

If you want your code to be more specific when casting the data, you could also cast it to the default Episerver objects:

As seen on Line 2, the code casts the object to VariationContent. If you working with a product you can also use ProductContent

NOTE: If you want to learn how to do the same within Episerver CMS, readHow do I get the “CurrentPage” from a controller ? deals with a similar principle.

You now know how to get Episerver Commerce products and variations directly out of the HTTP context object. Simply, use the data held in currentContent in the RouteData table and cast it to the object you care about. The code is pretty simple and straightforward, however, it can be tricky to figure this stuff out yourself so I hope this tutorial has saved you some time. Happy Coding 🤘