Problem with mapping in scheduled task

We have a problem with mapping a Page to PageModel in scheduled task. Query returns results but pageModel is null after mapping.

var page = query.FirstOrDefault();
if(page != null){
	var pageModel = page.MapTo<PageModel>();
}

(We had a similar problem in Problem with mapping after API request and since that was an API call we solved it with a change in RequestModelHandler, but we can’t use that solution here since this is not an API call?)

Any ideas?

Litium version: 7.1.0

The mapping for the PageModel is using the information from RouteRequestLookupInfo to see if the page is published for the specified channel. If the the page not is published it will return null, the same if the RouteRequestLookupInfo not is set in the RouteRequestLookupInfoAccessor. (same problem as you have in the linked thread.

FYI, the way we solved it before was a change in RequestModelHandler.cs, if it is an external API request and siteSettingViewModel is null then we create a new siteSettingViewModel with a specific value for channel:

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    var siteSettingViewModel = request.Headers.GetSiteSettingViewModel();
    if (siteSettingViewModel == null && IsApiRequest(request.RequestUri.ToString()))
    {
        siteSettingViewModel = new SiteSettingViewModel
        {
            ChannelSystemId = new Guid("9c0600d9-1c04-4a06-a2ce-ecaa58d8be50")
        };
    }
    ...
}

But I still don’t understand how we should fix it in this case. How do we set a channel for a scheduled task? Should we modify RouteRequestLookupInfo somehow?

In general you should inject RouteRequestLookupInfoAccessor and then do something like
_routeRequestLookupInfoAccessor.RouteRequestLookupInfo = new RouteRequestLookupInfo{ Channel = channelToWorkOn };. It can also be other settings that you need to set to make it work all the way.

What does your schedule task do? Why do you need a PageModel? RouteRequest and Channel are taken into account when mapping PageModel to Page. Can you try new PageModel(page)?

Thanks! The suggestion from @patric.forsgard solved our problem. We do like this.

public class MyTask : ITask
{
    private readonly RouteRequestLookupInfoAccessor _routeRequestLookupInfoAccessor;
    private readonly ChannelService _channelService;

    public MyTask(RouteRequestLookupInfoAccessor routeRequestLookupInfoAccessor, ChannelService channelService)
    {
        _routeRequestLookupInfoAccessor = routeRequestLookupInfoAccessor;
        _channelService = channelService;
    }

    public void ExecuteTask(SecurityToken token, string parameters)
    {
        var channel = _channelService.Get(new Guid("9c0600d9-1c04-4a06-a2ce-ecaa58d8be50"));
        _routeRequestLookupInfoAccessor.RouteRequestLookupInfo = new RouteRequestLookupInfo { Channel = channel };
        ...
    }
}