Categories Web Forms

Disabling mobile master pages with ASP.NET Friendly URLs

ASP.NET Friendly URLs automatically configures default routes that:

  1. drop the .aspx extension, and
  2. redirect to mobile .Mobile.aspx pages, inclusive of .Mobile.Master pages.

While I want the default routes to drop the .aspx extension, I don’t want the default routes to redirect to a mobile version. Unfortunately, I haven’t been able to find a way to disable the latter with Microsoft.AspNet.FriendlyUrls.Core 1.0.2. I use responsive web design to reflow content on mobile devices and avoid maintaining a second presentation layer with .Mobile.aspx pages. While I can happily ignore any .Mobile.aspx pages, deleting the included Site.Mobile.Master page when installing ASP.NET Friendly URLs or creating any new master pages causes my web application to generate an error that it can’t find a mobile version of the master page.

To resolve this issue, I’ve hacked together a custom WebFormsFriendlyUrlResolver that does not attempt to retrieve a mobile version of a master page (which generates the error):

''' <summary>
''' HACK: Disable ".Mobile.Master" master pages.
''' </summary>
Public Class MyWebFormsFriendlyUrlResolver
	Inherits Microsoft.AspNet.FriendlyUrls.Resolvers.WebFormsFriendlyUrlResolver

	''' <summary>
	''' Disable ".Mobile.Master" master pages.
	''' </summary>
	Protected Overrides Function TrySetMobileMasterPage(httpContext As HttpContextBase, page As UI.Page, mobileSuffix As String) As Boolean
		If mobileSuffix = "Mobile" Then
			Return False
			Return MyBase.TrySetMobileMasterPage(httpContext, page, mobileSuffix)
		End If
	End Function
End Class

I then register this custom WebFormsFriendlyUrlResolver in App_Start/RouteConfig.vb in my web application:

Imports System.Web.Routing
Imports Microsoft.AspNet.FriendlyUrls

Public Module RouteConfig

	Public Sub RegisterRoutes(ByVal routes As RouteCollection)
		Dim settings As FriendlyUrlSettings = New FriendlyUrlSettings()
		settings.AutoRedirectMode = RedirectMode.Permanent
		routes.EnableFriendlyUrls(settings, New Microsoft.AspNet.FriendlyUrls.Resolvers.IFriendlyUrlResolver() {New MyWebFormsFriendlyUrlResolver()})
	End Sub
End Module

I can now remove Site.Mobile.Master, ViewSwitcher.ascx and ignore creating .Mobile.Master pages without causing my web application to error when viewed on mobile devices.

I realise this is a hack, however this is the best solution I’ve been able to come up. Do you know how to disable the default routes for mobile devices? Please send me a comment and enlighten me to a more robust solution.


Thanks to: