using System; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.Extensions.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.Common.Routing; using Umbraco.Web.Routing; namespace Umbraco.Web.Common.Controllers { /// /// An abstract controller for a front-end Umbraco page /// public abstract class UmbracoPageController : UmbracoController { private UmbracoRouteValues _umbracoRouteValues; private readonly ICompositeViewEngine _compositeViewEngine; private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// protected UmbracoPageController(ILogger logger, ICompositeViewEngine compositeViewEngine) { _logger = logger; _compositeViewEngine = compositeViewEngine; } /// /// Gets the /// protected virtual UmbracoRouteValues UmbracoRouteValues { get { if (_umbracoRouteValues != null) { return _umbracoRouteValues; } _umbracoRouteValues = HttpContext.Features.Get(); if (_umbracoRouteValues == null) { throw new InvalidOperationException($"No {nameof(UmbracoRouteValues)} feature was found in the HttpContext"); } return _umbracoRouteValues; } } /// /// Gets the current content item. /// protected virtual IPublishedContent CurrentPage { get { if (!UmbracoRouteValues.PublishedRequest.HasPublishedContent()) { // This will never be accessed this way since the controller will handle redirects and not founds // before this can be accessed but we need to be explicit. throw new InvalidOperationException("There is no published content found in the request"); } return UmbracoRouteValues.PublishedRequest.PublishedContent; } } /// /// Gets an action result based on the template name found in the route values and a model. /// /// The type of the model. /// The model. /// The action result. /// If the template found in the route values doesn't physically exist and exception is thrown protected IActionResult CurrentTemplate(T model) { if (EnsurePhsyicalViewExists(UmbracoRouteValues.TemplateName) == false) { throw new InvalidOperationException("No physical template file was found for template " + UmbracoRouteValues.TemplateName); } return View(UmbracoRouteValues.TemplateName, model); } /// /// Ensures that a physical view file exists on disk. /// /// The view name. protected bool EnsurePhsyicalViewExists(string template) { ViewEngineResult result = _compositeViewEngine.FindView(ControllerContext, template, false); if (result.View != null) { return true; } _logger.LogWarning("No physical template file was found for template {Template}", template); return false; } } }