I have an MVC .Net application and am struggling to put the prismic preview working.
Basically when I put the following script in the page, the page reloads and overrides the cookie and then I am getting the normal data instead of the changes. That reload seems to happen due to this script that prismic is advising to put on the page:
<script async defer src="https://static.cdn.prismic.io/prismic.js?new=true&repo=MY_REPO"></script>
Here it is my Preview Action:
const string isPreviewParam = "isPreview=1";
public async Task<ActionResult> Preview(string token)
{
var ctx = await getContext(false);
string url = await ctx.Api.PreviewSession (token, ctx.LinkResolver, "/") + "&" + isPreviewParam;
var cookie = new HttpCookie (prismic.Api.PREVIEW_COOKIE, token);
cookie.Expires = DateTime.Now.AddMinutes (30);
this.ControllerContext.HttpContext.Response.SetCookie(cookie);
return Redirect(url);
}
Action to show the page:
public async Task<ActionResult> Detail(string id, string slug)
{
var ctx = await getContext(isPreview(HttpContext.Request.Url.ToString()));
var response = await ctx.Api.Form("everything")
.Query(Predicates.at("document.id", id))
.Ref (ctx.MaybeRef)
.Submit ();
var document = response.Results.FirstOrDefault ();
if (document != null && document.Slug == slug) {
ViewBag.Title = "Document detail " + slug;
return View (new PrismicDocument (ctx, document));
}
else if (document != null && document.Slugs.Contains(slug)) {
return RedirectToActionPermanent ("Detail", new { id, document.Slug });
} else {
ViewBag.Title = "Document not found";
this.Response.StatusCode = 404;
return View ("PageNotFound", new PrismicViewModel(ctx));
}
}
And the get context method:
private async Task<PrismicContext> getContext(bool isPreview)
{
var endpoint = WebConfigurationManager.AppSettings.Get("prismic.api.url");
var api = await new PrismicApiHome(endpoint).Get();
HttpCookie previewCookie = isPreview ? HttpContext.Request.Cookies.Get(prismic.Api.PREVIEW_COOKIE) : null;
string maybeRef = (previewCookie != null && previewCookie.Value != "")
? previewCookie.Value
: api.Master.Reference;
return new PrismicContext(endpoint, api, maybeRef, PrismicLinkResolver.Get(api, maybeRef, ControllerContext.RequestContext));
}
This how the cookie looks like when I remove the JavaScript mentioned above (without reloading)
This how the cookie looks like with the JavaScript, it reloads and smashed the previous cookie value and I see the live prismic value instead of the preview.
Any idea why? What am I doing wrong?