Created
November 4, 2014 15:19
-
-
Save AndyButland/4ce3836600750b80986e to your computer and use it in GitHub Desktop.
Umbraco redirect to parent with template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RedirectNodesWithoutTemplate : ApplicationEventHandler | |
{ | |
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ | |
PublishedContentRequest.Prepared += PublishedContentRequest_Prepared; | |
base.ApplicationStarted(umbracoApplication, applicationContext); | |
} | |
private void PublishedContentRequest_Prepared(object sender, System.EventArgs e) | |
{ | |
var request = sender as Umbraco.Web.Routing.PublishedContentRequest; | |
if (request != null && request.HasPublishedContent) | |
{ | |
if (!request.HasTemplate) | |
{ | |
var ancestorWithTemplate = request.PublishedContent | |
.Ancestors() | |
.Where(x => x.TemplateId != 0) | |
.OrderByDescending(x => x.Level) | |
.FirstOrDefault(); | |
if (ancestorWithTemplate != null) | |
{ | |
request.SetRedirect(ancestorWithTemplate.Url); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment