ASP.NET MVC - 捕获所有路由和默认路由 [英] ASP.NET MVC - Catch All Route And Default Route

查看:41
本文介绍了ASP.NET MVC - 捕获所有路由和默认路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了让我的应用程序正确产生 404 错误,我在路由表的末尾实现了一个捕获所有路由,如下所示:

In trying to get my application to produce 404 errors correctly, I have implemented a catch all route at the end of my route table, as shown below:

 routes.MapRoute(
            "NotFound", _
           "{*url}", _
           New With {.controller = "Error", .action = "PageNotFound"} _
       )

但是,要使其正常工作,我必须删除默认路由:

However, to get this working, I had to remove the default route:

{controller}/action/{id}

但现在默认值已被删除,我的大部分操作链接不再有效,我发现让它们再次工作的唯一方法是为每个控制器/操作添加单独的路由.

But now that the default has been removed, most of my action links no longer work, and the only way I have found to get them working again is to add individual routes for each controller/action.

有没有更简单的方法来做到这一点,而不是为每个控制器/动作添加一个路由?

Is there a simpler way of doing this, rather than adding a route for each controller/action?

是否可以创建一个默认路由,如果用户尝试导航到未知路由,仍然允许捕获所有路由工作?

Is it possible to create a default route that still allows the catch all route to work if the user tries to navigate to an unknown route?

推荐答案

使用路由约束

在您的情况下,您应该定义默认路由 {controller}/{action}/{id} 并对其施加约束.可能与控制器名称甚至动作有关.然后把catch全部放在它后面,它应该可以正常工作.

Use route constraints

In your case you should define your default route {controller}/{action}/{id} and put a constraint on it. Probably related to controller names or maybe even actions. Then put the catch all one after it and it should work just fine.

因此,当有人请求未通过约束的资源时,catch-all 路由将匹配请求.

So when someone would request a resource that fails a constraint the catch-all route would match the request.

所以.首先使用路由约束定义默认路由,然后在它之后捕获所有路由:

So. Define your default route with route constraints first and then the catch all route after it:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { controller = "Home|Settings|General|..." } // this is basically a regular expression
);
routes.MapRoute(
    "NotFound",
    "{*url}",
    new { controller = "Error", action = "PageNotFound" }
);

这篇关于ASP.NET MVC - 捕获所有路由和默认路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆