Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Text.RegularExpressions;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace MobileTest
- {
- /*
- * Add the global filer RedirectMobileDevicesToMobileAreaAttribute to the global filter collection in
- * the Application_Start() of Global.asax.cs file
- *
- * GlobalFilters.Filters.Add(new RedirectMobileDevicesToMobileAreaAttribute(), 1);
- *
- * Add a reference to "51Degrees.mobi" library using NuGet
- *
- * See: http://weblogs.asp.net/shijuvarghese/archive/2011/02/25/mobile-enabled-web-apps-with-asp-net-mvc-3-and-jquery-mobile.aspx
- * http://aspnetmobilesamples.codeplex.com/
- *
- * How to configure areas in MVC3:
- * http://2010wave.blogspot.com/2009/12/how-to-create-areas-in-aspnet-mvc.html
- * http://stackoverflow.com/questions/5243158/how-to-configure-areas-in-asp-net-mvc3
- */
- public class RedirectMobileDevicesToMobileAreaAttribute : AuthorizeAttribute
- {
- /// <summary>
- /// When overridden, provides an entry point for custom authorization checks.
- /// </summary>
- /// <param name="httpContext">The HTTP context, which encapsulates all HTTP-specific information about an individual HTTP request.</param>
- /// <returns>
- /// true if the user is authorized; otherwise, false.
- /// </returns>
- /// <exception cref="T:System.ArgumentNullException">The <paramref name="httpContext"/> parameter is null.</exception>
- protected override bool AuthorizeCore(HttpContextBase httpContext)
- {
- // Only redirect on the first request in a session
- if (!httpContext.Session.IsNewSession)
- return true;
- // Don't redirect non-mobile browsers
- if (!httpContext.Request.Browser.IsMobileDevice)
- return true;
- // Don't redirect requests for the Mobile area
- if (Regex.IsMatch(httpContext.Request.Url.PathAndQuery, "/Mobile($|/)"))
- return true;
- return false;
- }
- /// <summary>
- /// Gets the redirection route values.
- /// </summary>
- /// <param name="requestContext">The request context.</param>
- /// <returns></returns>
- protected virtual RouteValueDictionary GetRedirectionRouteValues(RequestContext requestContext)
- {
- return new RouteValueDictionary(new { area = "Mobile", controller = "Home", action = "Index" });
- }
- /// <summary>
- /// Processes HTTP requests that fail authorization.
- /// </summary>
- /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute"/>. The <paramref name="filterContext"/> object contains the controller, HTTP context, request context, action result, and route data.</param>
- protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
- {
- var redirectionRouteValues = GetRedirectionRouteValues(filterContext.RequestContext);
- filterContext.Result = new RedirectToRouteResult(redirectionRouteValues);
- }
- }
- }
Add Comment
Please, Sign In to add comment