.net-5episerveroptimizely

HttpContextAccessor.HttpContext is null in blocks and in @sections


I'm doing migration from episerver 11 to 12 and in views have this problem:

In all blocks and and in @section on @Html.PropertyFor always get this exeption:

Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer[2]
      Connection ID "17293822592188153887", Request ID "80000020-0005-f000-b63f-84710c7967bb": An unhandled exception was thrown by the application.
      System.NullReferenceException: Object reference not set to an instance of an object.
         at EPiServer.Web.HttpContextExtensions.ContentRenderingContext(HttpContext httpContext)
         at EPiServer.Web.Mvc.Html.Internal.DeferredHtmlContent..ctor(Action`1 action, HttpContext httpContext)
         at EPiServer.Web.Mvc.Html.PropertyRenderer.GetHtmlForDefaultMode[TModel,TValue](String propertyName, String templateName, String elementName, String elementCssClass, Func`2 displayForAction)
         at EPiServer.Web.Mvc.Html.PropertyRenderer.PropertyFor[TModel,TValue](IHtmlHelper`1 html, String viewModelPropertyName, Object additionalViewData, Object editorSettings, Expression`1 expression, Func`2 displayForAction)
         at EPiServer.Web.Mvc.Html.PropertyExtensions.PropertyFor[TModel,TValue](IHtmlHelper`1 html, Expression`1 expression)
         at AspNetCore.Areas_Main_Views_Shared_Layouts__BaseHtmlBlock.ExecuteAsync() in *MY VIEW NAME*

I've debugged the decompiled code and in ContentRenderingContext HttpContextAccessor exists but the HttpContext inside it is null.

When I try to inject IHttpContextAccessor in block controller it has HttpContext null.

BUT - if i try to get it in page controller and page view (@Html.PropertyFor) it works fine a and HttpContext exists.

In Startup.cs i have it applied like this:

services.AddHttpContextAccessor();

What is wrong? Do I have to do anything else?

Edit: If I do this, then error resolves, but this doesn't look good and I don't want to copy-paste it everywhere.

For section:

@section Footer {
    @{
        ServiceLocator.Current.GetInstance<IHttpContextAccessor>().HttpContext = Context;
    }
    
    @Html.PropertyFor(x => x.CurrentPage.FooterBottomContentArea)
}

For Block (after injecting HttpContextAccessor in InvokeComponent):

HttpContextAccessor.HttpContext = HttpContext;

Solution

  • We dicovered that this issue is resolved in the newer version of episerver, we updated from 12.3 to 12.6 and PropertyFor is working everywhere now.

    I decompiled it and I see that in GetHtmlForDefaultMode it uses WrappedHtmlContent in the newest version and doesn't use HttpContextAccessor at all.