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