Search code examples
c#episerver

EPiServer - How can I get current page data?


I am working on EPiServer. I am creating a plugin to edit content of current page. I am trying to get the data from the code following:

 var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IPageRouteHelper>();

 var currentPage = pageRouteHelper.Page;

but every time the currentPage returns me the content of the start page. What is missing here and I cannot get the page I have open on screen content?


Solution

  • If we have the page id, for instance 139, with the following code we can retrieve the page's content.

    var pageId = 139;
    
    var pageRef = new PageReference(pageId);
    
    var contentRepository = ServiceLocator.Current.GetInstance<IContentLoader>();
    
    var page = contentRepository.Get<PageData>(pageRef);
    

    A simply, but may not the most practical way, to get the page id from the browser is

    var pageUrl = HttpContext.Current.Request.RawUrl;
    

    From the pageUrl we can retrieve the pageId.