The UmbracoContext is a helpful service provided on each request to the website
The UmbracoContext is the simplified way to work with the current request on your website.
You can use UmbracoContext to access the content and media cache. Other useful properties are the original and cleaned URLs of the current request. You can also check if the current request is running in "preview" mode.
How to reference UmbracoContext
If you are using Views you can reference the UmbracoContext with the syntax: @UmbracoContext
If you need an UmbracoContext in your own controllers, you need to inject an IUmbracoContextAccessor.
The following is an example of how to get access to the UmbracoContext in a controller:
The example below uses UmbracoApiController which is obsolete in Umbraco 14 and will be removed in Umbraco 15.
usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingMicrosoft.AspNetCore.Mvc;usingUmbraco.Cms.Core.Web;usingUmbraco.Cms.Web.Common.Controllers;usingUmbraco.Cms.Web.Common.PublishedModels;usingUmbraco.Extensions;namespaceUmbraco.Docs.Samples.Web.Controllers.Api;publicclassPeopleController:UmbracoApiController{privatereadonlyIUmbracoContextAccessor _umbracoContextAccessor;publicPeopleController(IUmbracoContextAccessor umbracoContextAccessor) { _umbracoContextAccessor = umbracoContextAccessor; } [HttpGet]publicActionResult<IEnumerable<string>> GetAll() {if (_umbracoContextAccessor.TryGetUmbracoContext(outIUmbracoContext? context) ==false) {returnthis.Problem("unable to get content"); }if (context.Content==null) {returnthis.Problem("Content Cache is null"); }var personContentType =context.Content.GetContentType(Person.ModelTypeAlias);Debug.Assert(context.Content.HasContent());var personNodes = (context.Content.GetAtRoot() .First() .FirstChild<People>() .Children<Person>() ??Array.Empty<Person>()) .Select(p =>p.Name);return personContentType ==null?this.Problem("Person Content Type is null"):Ok(personNodes); }}
UmbracoContext is registered with a scoped lifetime. See the Microsoft documentation for more information. A service scope is created for each request, which means you can resolve an instance directly in a controller.