用户使用IE时重定向

时间:2012-11-24 07:13:54

标签: asp.net-mvc routing

我在ASP.NET MVC中创建了这个自定义路由类:

public class UserAgentConstraint:IRouteConstraint {
  private string RequiredUserAgent;
  public UserAgentConstraint(string agentParam) {
    RequiredUserAgent = agentParam;
  }
  public bool Match(HttpContextBase httpContext, Route route, string parameterName,
    RouteValueDictionary values, RouteDirection routeDirection) {
    return httpContext.Request.UserAgent != null && !httpContext.Request.UserAgent.Contains(RequiredUserAgent);
  }
}

在Global.asax.cs中:

public static void RegisterRoutes(RouteCollection routes) {
  routes.MapRoute("myRoute2", "{controller}/{action}/{Id}",
    new { controller = "home", action = "index", Id = UrlParameter.Optional }, new {
      customConstriant=new UserAgentConstraint("IE")
    }
  }

上面的代码完美地工作,但是当用户使用IE时,我得到404错误。我想重定向到自定义页面。我不想在Web.Config文件中使用自定义错误,因为我的错误仅用于IE。怎么能这样做?

谢谢你的建议。

1 个答案:

答案 0 :(得分:4)

更好的方法是使用ActionFilter。

    public class BrowserFilterAttribute : ActionFilterAttribute 
    {
        public string [] _browserNames { get; set; }
        public AssetIdFilterAttribute(params string [] browserNames)
        {
            _browserNames= browserNames;
        }


        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {            
            //get browser name from somewhere
            string currentBrowser  = filterContext.HttpContext.Request.Browser.Browser;
            if(_browserNames.Contains(currentBrowser))
                filterContext.Result = new RedirectResult("your URL");
        }

    }

您可以在控制器级别应用它,如下所示:

  [BrowserFilter("IE","Opera","SomeOtherBrowser")]
  public class BrowserAwareController() : Controller
  {

  } 
希望这有帮助。祝你好运。