How To Get The Current Page in Sitecore
When you start building any web project, one of the first things that you will need to do is get information about the current page to display related page data back to the website user. In today's tutorial, I'm going to cover some of the basic API calls to achieve this.
Sitecore InstanceTo get information about the current item, you can use the Sitecore Context. Like the normal HttpContext, the Sitecore context, as the name suggests, gives you information about the current request.
Sitecore.Context.ItemThe Sitecore.Context.item has a number of useful properties. For example, if you want to know if the current page is being viewed in a Sitecore preview, or, from the website you can use this code:
Get current page URL from Sitecore APIUsing the Sitecore.Context we can then use the LinkManager to get the current pages Url like so:
var currentUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);
Change is coming..Ok, so for years and years the Sitecore context was the only way to get information about the current request, however, with the DMS and MVC using Sitecore.Context isn't always the best approach.
Sitecore MVC HelpersIn our Razor views, we might want to get Sitecore information. Personally, I would strongly discourage doing this as it breaks the point of MVC. By using these helpers you are adding business logic into your views. It's a much better technique to put all your Sitecore logic in View Models and pass them into your views. For reference, though, here are the helpers:
Page Contextif you are trying to write code about the current request in a rendering, you may want to look at the page Context. In the context of a rendering, the page item is the root item that will be rendered. In these instances you can use the pgeContext to get the information:
1 var page = PageContext.Current.Item;