> For the complete documentation index, see [llms.txt](https://docs.umbraco.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.umbraco.com/umbraco-cms/17.latest/develop-with-umbraco/templating-and-rendering/querying/umbraco-context.md).

# UmbracoContext Helper

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:

```csharp
using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Web;

namespace MyProject.Controllers.Api;

[ApiController]
[Route("/umbraco/api/people")]
public class PeopleController : Controller
{
    private readonly IUmbracoContextAccessor _umbracoContextAccessor;
    private readonly IPublishedContentQuery _publishedContentQuery;

    public PeopleController(
        IUmbracoContextAccessor umbracoContextAccessor,
        IPublishedContentQuery publishedContentQuery)
    {
        _umbracoContextAccessor = umbracoContextAccessor;
        _publishedContentQuery = publishedContentQuery;
    }

    [HttpGet("getall")]
    public ActionResult<IEnumerable<string>> GetAll()
    {
        // Try to get the UmbracoContext
        if (_umbracoContextAccessor.TryGetUmbracoContext(out IUmbracoContext? context) == false)
        {
            return Problem("Unable to get UmbracoContext");
        }

        // Check if we're in preview mode using UmbracoContext
        if (context.InPreviewMode)
        {
            // In preview mode, you might want to show draft content or additional info
            return Ok(new
            {
                message = "Preview mode active",
                isPreview = true
            });
        }

        if (context.Content == null)
        {
            return Problem("Content Cache is null");
        }

        // Use IPublishedContentQuery to get root content
        var rootNodes = _publishedContentQuery.ContentAtRoot();

        if (!rootNodes.Any())
        {
            return Problem("No content found at root");
        }

        // Find a specific parent node (for example, "People" section)
        var peopleNode = rootNodes
            .FirstOrDefault()?
            .Children()
            .FirstOrDefault(c => c.ContentType.Alias == "people");

        if (peopleNode == null)
        {
            return Problem("People node not found");
        }

        // Get only the direct children of the People node
        var personNodes = peopleNode.Children()
            .Where(c => c.ContentType.Alias == "person")
            .Select(p => p.Name);

        // Return results with UmbracoContext information
        return Ok(new
        {
            people = personNodes,
            // Include UmbracoContext properties in the response
            contextInfo = new
            {
                isPreview = context.InPreviewMode,
                currentUrl = context.CleanedUmbracoUrl?.ToString()
            }
        });
    }
}
```

{% hint style="info" %}
For content querying scenarios, use `IPublishedContentQuery.ContentAtRoot()`.

For advanced navigation, multi-site setups, or culture-specific root detection, use `IDocumentNavigationQueryService.TryGetRootKeys()`, which returns GUID keys representing the structure of the content tree.
{% endhint %}

UmbracoContext is registered with a scoped lifetime. See the [Microsoft documentation](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#lifetime-and-registration-options) for more information. A service scope is created for each request, which means you can resolve an instance directly in a controller.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.umbraco.com/umbraco-cms/17.latest/develop-with-umbraco/templating-and-rendering/querying/umbraco-context.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
