Created
November 14, 2012 11:36
-
-
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
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
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@leekelleher do you have a version for 7.1.8?