umbraco / Umbraco-CMS

Umbraco is a free and open source .NET content management system helping you deliver delightful digital experiences.
https://umbraco.com
MIT License
4.49k stars 2.69k forks source link

IVirtualPageController doesn't set the context correctly #15531

Open akay0214 opened 10 months ago

akay0214 commented 10 months ago

Which Umbraco version are you using? (Please write the exact version, example: 10.1.0)

13.0.3

Bug summary

The custom route with UmbracoPageController and IVirtualPageController doesn't set PublishedContent correctly in the Umbraco context. As a result, current PublishedContent is not available from aspnet core ViewComponent code.

Specifics

No response

Steps to reproduce

0. Create the following structure in Umbraco:

Let's assume Details item has an id equal to 1022. Default Umbraco urls for these items will be /item and /item/details.

1. Create a virtual page controller to handle custom urls like /item/123

123 - can be a random id

public class DetailsController : UmbracoPageController, IVirtualPageController
{
    public DetailsController(
        IUmbracoContextAccessor umbracoContextAccessor,
        ILogger<UmbracoPageController> baseLogger,
        ICompositeViewEngine compositeViewEngine
    ) : base(baseLogger, compositeViewEngine)
    {
        _umbracoContextAccessor = umbracoContextAccessor;
        _logger = logger;
        _publishedValueFallback = publishedValueFallback;
    }

    public IPublishedContent? FindContent(ActionExecutingContext actionExecutingContext)
    {
        if (_umbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext))
        {
            var content = umbracoContext.Content.GetById(1387);
            if (content != null) return content;
        }
        return null;
    }

    [HttpGet]
    public IActionResult Index()
    {
        return View(CurrentPage);
    }

    private readonly IUmbracoContextAccessor _umbracoContextAccessor;
    private readonly ILogger<ConnectionDetailsController> _logger;
    private readonly IPublishedValueFallback _publishedValueFallback;
}

2. Register a custom MVC route with a composer

public class RoutesComposer : IComposer
{
    public void Compose(IUmbracoBuilder builder)
    {
        builder.Services.Configure<UmbracoPipelineOptions>(
            options =>
            {
                options.AddFilter(
                    new UmbracoPipelineFilter(nameof(DetailsController))
                    {
                        Endpoints = app => app.UseEndpoints(
                            endpoints =>
                            {
                                endpoints.MapControllerRoute(
                                    "Details controller",
                                    "/item/{id}",
                                    new { Controller = "Details", Action = "Index" }
                                );
                            }
                        )
                    }
                );
            }
        );
    }
}

3. Add a ViewComponent to the View returned from the Index action

For example:

@await Component.InvokeAsync("DetailsHeader")

The final piece is an implementaiton of the ViewComponent, which works in the context of the Current Umbraco Item:

[ViewComponent(Name = "DetailsHeader")]
public class DetailsHeader : ViewComponent
{
    public DetailsHeader(
        IUmbracoContextAccessor context,
        IConfiguration configuration,
        IPublishedValueFallback publishedValueFallback
    )
    {
        _context = context;
        _configuration = configuration;
        _publishedValueFallback = publishedValueFallback;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var viewModel = GetViewModel();
        return await Task.FromResult((IViewComponentResult)View(viewModel));
    }

    private PageSeoViewModel GetViewModel()
    {
        var content = _context.GetRequiredUmbracoContext().PublishedRequest.PublishedContent; // PublishedContent is null
        var detailsHeader = new Models.Generated.DetailsHeader(content, _publishedValueFallback);

        var viewModel = new detailsHeaderViewModel();
        viewModel.Title = detailsHeader.Title
        viewModel.Description = detailsHeader.Description;

        return viewModel;
    }

    private readonly IUmbracoContextAccessor _context;
    private readonly IConfiguration _configuration;
    private readonly IPublishedValueFallback _publishedValueFallback;
}

4. Access /item/123 url

Expected result / actual result

Actual result

The _context.GetRequiredUmbracoContext().PublishedRequest.PublishedContent property always returns null. As a result, you'll see on the screen something like:

NullReferenceException: Object reference not set to an instance of an object.
Umbraco.Cms.Core.Models.PublishedContent.PublishedElementWrapped.GetProperty(string alias)
Umbraco.Extensions.PublishedElementExtensions.Value<T>(IPublishedElement content, IPublishedValueFallback publishedValueFallback, string alias, string culture, string segment, Fallback fallback, T defaultValue)

Expected result

Since I IVirtualPageController interface implementation is responsible for resolving content, it should set it to the UmbracoContext correctly. So ViewComponents can use the context as on the regular Umbraco item page.

github-actions[bot] commented 10 months ago

Hi there @akay0214!

Firstly, a big thank you for raising this issue. Every piece of feedback we receive helps us to make Umbraco better.

We really appreciate your patience while we wait for our team to have a look at this but we wanted to let you know that we see this and share with you the plan for what comes next.

We wish we could work with everyone directly and assess your issue immediately but we're in the fortunate position of having lots of contributions to work with and only a few humans who are able to do it. We are making progress though and in the meantime, we will keep you in the loop and let you know when we have any questions.

Thanks, from your friendly Umbraco GitHub bot :robot: :slightly_smiling_face:

Zeegaan commented 10 months ago

Aha, I can certainly reproduce this, thanks for the detailed steps 💪 🐛

github-actions[bot] commented 10 months ago

Hi @akay0214,

We're writing to let you know that we would love some help with this issue. We feel that this issue is ideal to flag for a community member to work on it. Once flagged here, folk looking for issues to work on will know to look at yours. Of course, please feel free work on this yourself ;-). If there are any changes to this status, we'll be sure to let you know.

For more information about issues and states, have a look at this blog post.

Thanks muchly, from your friendly Umbraco GitHub bot :-)