Sir*_*ifi 1 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);
}
}
Run Code Online (Sandbox Code Playgroud)
在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")
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码可以正常工作,但是当用户使用IE时,出现404错误。我想重定向到自定义页面。我不想在Web.Config文件中使用自定义错误,因为我的错误仅在IE中使用。一个人怎么能做到呢?
感谢您的建议。
更好的方法是使用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");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以像下面这样在控制器级别应用它:
[BrowserFilter("IE","Opera","SomeOtherBrowser")]
public class BrowserAwareController() : Controller
{
}
Run Code Online (Sandbox Code Playgroud)
希望这个帮助。祝你好运。
| 归档时间: |
|
| 查看次数: |
712 次 |
| 最近记录: |