Created
December 13, 2012 14:45
-
-
Save kevinblake/4276803 to your computer and use it in GitHub Desktop.
MVC4 action filter attribute to redirect to a different controller if a page is not valid for mobile/non-mobile context
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.Web.Mvc; | |
using System.Web.Routing; | |
using System.Web.WebPages; | |
namespace MyNamespace | |
{ | |
public enum DeviceType {Mobile, Desktop} | |
public class DeviceTypeRedirect : ActionFilterAttribute | |
{ | |
public string RedirectController { get; set; } | |
public string RedirectAction { get; set; } | |
public DeviceType RedirectOnDevice { get; set; } | |
public override void OnActionExecuting(ActionExecutingContext filterContext) | |
{ | |
base.OnActionExecuting(filterContext); | |
if (filterContext.HttpContext.GetOverriddenBrowser().IsMobileDevice == (this.RedirectOnDevice == DeviceType.Mobile)) | |
{ | |
this.RedirectToRoute(filterContext, new { controller = this.RedirectController, action = this.RedirectAction }); | |
} | |
} | |
private void RedirectToRoute(ActionExecutingContext context, object routeValues) | |
{ | |
var rc = new RequestContext(context.HttpContext, context.RouteData); | |
var virtualPathData = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(routeValues)); | |
if (virtualPathData != null) | |
{ | |
string url = virtualPathData.VirtualPath; | |
context.HttpContext.Response.Redirect(url, true); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment