.Net MVC中访问PC网页时,自动切换到移动端对应页面
随着移动端的流行,越来越的网站,除了提供PC网页之外,也提供了移动端的H5页面,手机在访问www.xxx.com的时候,能自动跳转到mobile.xxx.com。网上很多在实现时也能使用JS直接进行跳转,除了JS之外,你还可以使用MVC的后端代码直接实现
一、核心代码
HttpContext.Current.Request.Browser.IsMobileDevice
二、如何使用 ?
方法一:
在首页访问Controller代码最前面直接增加核心代码进行判断
public ActionResult Index() { if (IsMobile()) { return Redirect("mobile.xxx.com"); } return View(); } public static bool IsMobile() { if (System.Web.HttpContext.Current.Request.Browser.IsMobileDevice) return true; return false; }
方法二
继承AuthorizeAttribute,增加自定义Attribute
public class RedirectMobileDevicesToMobileAreaAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { RouteData rData = httpContext.Request.RequestContext.RouteData; //判断,如果是页面手工点击的【电脑版】,则不进行跳转 string customChange = (rData.Values["id"] ?? "").ToString(); if (!string.IsNullOrWhiteSpace(customChange)) { return true; } if (!httpContext.Session.IsNewSession) return true; if (!httpContext.Request.Browser.IsMobileDevice) return true; if (Regex.IsMatch(httpContext.Request.Url.PathAndQuery, "/Mobile($|/)")) return true; return false; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { var redirectionRouteValues = GetRedirectionRouteValues(filterContext.RequestContext); filterContext.Result = new RedirectToRouteResult(redirectionRouteValues); } protected virtual RouteValueDictionary GetRedirectionRouteValues(RequestContext requestContext) { return new RouteValueDictionary(new { area = "Mobile", controller = requestContext.RouteData.Values["controller"], action = requestContext.RouteData.Values["action"] }); } }
在需要跳转的地方增加
[RedirectMobileDevicesToMobileArea]
[RedirectMobileDevicesToMobileArea] public ActionResult Index() { //if (IsMobile()) //{ // return Redirect("mobile.xxx.com"); //} return View(); }