using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web.Common.Filters;
using Umbraco.Web.Common.Routing;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Common.Controllers
{
///
/// Represents the default front-end rendering controller.
///
[TypeFilter(typeof(ModelBindingExceptionFilter))]
public class RenderController : UmbracoController, IRenderController
{
private readonly ILogger _logger;
private readonly ICompositeViewEngine _compositeViewEngine;
private UmbracoRouteValues _routeValues;
///
/// Initializes a new instance of the class.
///
public RenderController(ILogger logger, ICompositeViewEngine compositeViewEngine)
{
_logger = logger;
_compositeViewEngine = compositeViewEngine;
}
///
/// Gets the current content item.
///
protected IPublishedContent CurrentPage => UmbracoRouteValues.PublishedContent;
///
/// Gets the
///
protected UmbracoRouteValues UmbracoRouteValues
{
get
{
if (_routeValues != null)
{
return _routeValues;
}
if (!ControllerContext.RouteData.Values.TryGetValue(Core.Constants.Web.UmbracoRouteDefinitionDataToken, out var def))
{
throw new InvalidOperationException($"No route value found with key {Core.Constants.Web.UmbracoRouteDefinitionDataToken}");
}
_routeValues = (UmbracoRouteValues)def;
return _routeValues;
}
}
///
/// 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;
}
///
/// 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);
}
///
/// The default action to render the front-end view.
///
public virtual IActionResult Index() => CurrentTemplate(new ContentModel(CurrentPage));
}
}