IPageDataContextInitializer on WebAPI

Hadi Wijaya asked on October 15, 2023 17:01

Hi,

Currently, I am having an issue getting current page alias path in Web API project (using ASP.Net Core Web API project). I use IPageDataContextRetriever to retrieve the current TreeNode, however it return following error:

System.InvalidOperationException: 'Missing page context data. If required use IPageDataContextInitializer.Initialize method to initialize the context manually. For POST actions use HtmlHelper extension method Html.Kentico().PageData() to persist the page context.'

I tried to initialize the current page context using IPageDataContextInitializer.Initialize() as suggested above, however it only accept either the page id or TreeNode as parameter which the API does not have info about it.

I can pass the page id from the API caller (jQuery) to the API so I can initialize the page, however I wanna know if there's an easier way to get the current page context in Web API project without have to initialize it.

FYI, I am using Kentico 13.

Thank you if anyone can help with this.

Hadi

Recent Answers


Jono Rickard answered on October 18, 2023 22:42

Heya Hadi,

Yeah so this is an issue because when your API endpoint is called, kentico doesnt have the context of what page the user made the call from.

You can do something similar to what the error mentions - adding this line

@Html.Kentico().PageData()

into your page - this will generate a <input type="hidden" name="__Kentico_DC_Page" value="..."/> which has an encrypted string representing the DocumentID - which kentico uses to resolve the current page.

However since your making a call from JS rather than a form submission, you'll want to query the DOM for this input in JS and include it's name & vlaue in your AJAX request data.

There's a limitation on this though: The __Kentico_DC_Page=<value> field needs to be sent in the AJAX request with Content-Type: application/x-www-form-urlencoded.


Alternatively - you could do as you say and include the page id directly in a custom field in your AJAX request. As you mention IPageDataContextInitializer can be used to initialize the page with your custom field, which will then allow the IPageDataContextRetriever to work correctly as normal.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.