Skip to content

Instantly share code, notes, and snippets.

@brendankowitz
Created November 14, 2012 11:36
Show Gist options
  • Save brendankowitz/4071660 to your computer and use it in GitHub Desktop.
Save brendankowitz/4071660 to your computer and use it in GitHub Desktop.
Umbraco IHttpModule to switch to an optional [TemplateAlias]Mobile template when mobile devices are detected
using System;
using System.Linq;
using System.Web;
using Kowitz.Core.Module;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using ZeroProximity.DeviceDetection;
using umbraco;
using umbraco.cms.businesslogic.template;
[assembly: PreApplicationStartMethod(typeof(MobileRewriteModule), "Start")]
namespace Kowitz.Core.Module
{
public sealed class MobileRewriteModule : IHttpModule
{
readonly IMobileDeviceDetection _deviceDeviceDetection = DeviceDetectionFactory.GetDefaultImplementation();
void IHttpModule.Dispose() {
}
void IHttpModule.Init(HttpApplication application) {
application.PostResolveRequestCache += delegate(object sender, EventArgs e) {
if (application.Context.Items.Contains("pageID") == false) return;
var result = _deviceDeviceDetection.Match(application.Context.Request.UserAgent);
if (result.IsMobile)
{
var page = umbraco.NodeFactory.Node.GetCurrent();
if (application.Context.Request.Url.Query.Contains("?")) return;
var template = new template(page.template);
var tryGetMobileTemplate = Template.GetAllAsList().FirstOrDefault(x => x.Alias == template.TemplateAlias + "Mobile");
if (tryGetMobileTemplate != null)
{
application.Context.RewritePath(string.Format("{0}?alttemplate={1}", page.Url, tryGetMobileTemplate.Alias));
}
}
};
}
private static bool _startWasCalled;
public static void Start()
{
if (_startWasCalled) return;
_startWasCalled = true;
DynamicModuleUtility.RegisterModule(typeof(MobileRewriteModule));
}
}
}
@leekelleher
Copy link

You could hook into the "UmbracoDefault.AfterRequestInit" event? Would remove the need for using a HttpModule.

Example code snippet:

public class EventsHandler : ApplicationBase
{
    public EventsHandler()
    {
        UmbracoDefault.AfterRequestInit += new UmbracoDefault.RequestInitEventHandler(this.UmbracoDefault_AfterRequestInit);
    }

    private void UmbracoDefault_AfterRequestInit(object sender, RequestInitEventArgs e)
    {
        var url = e.Context.Request.Url.ToString().ToLower();
        var page = e.Page;
    }
}

@wiedikerli
Copy link

@leekelleher do you have a version for 7.1.8?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment