EPiServer Commerce : How do I get the current Product or Variant from a controller or attribute ?

There are certain circumstances when working with Episerver or Episerver commerce when you need to come off the beaten track and interact with the HTTP context a bit more closely.  For example, if you need to create a custom ActionFilterAttribute, or, you need to to do some routing wizardry with communication between blocks on your product pages.  One of my most popular tutorials EPiServer 7 : How do I get the “CurrentPage” from a controller ? deals with a similar principle.

The code below assumes that you are working with-in an ActionFilterAttribute but as long as you have access to the controller context the same principles apply to wherever.

Getting EntryContentBase from the HTTP context

var currentContent = filterContext.Controller.ControllerContext.RouteData.Values["currentContent"];
var entryContentBase = currentContent as EntryContentBase;

The first approach is the generic approach that will get you access to your product code.  This involves getting the currentContent out of the RouteData and typing it to an EntryContentBase.  Using this code will allow you to process products and variants at the same time.

Getting the Variant from the HTTP context

var currentContent = filterContext.Controller.ControllerContext.RouteData.Values["currentContent"];
var entryContentBase = currentContent as VariationContent;

If you want your code to be more specific to the data you are working on, then you simply type it to the default Episerver objects VariationContentor ProductContent.  In most scenarios you will be working with your own commerce types as you would usually

Conclusion

In today’s tutorial, we’ve covered how to commerce products and variations directly out of the HTTP context/controller context.  We use the currentContent key in the RouteData table and then type it to the object you care about.  The code is pretty simple and straightforward but can be a bit tricky at times to figure out yourself.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *