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

查看:520
本文介绍了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?

推荐答案

在你的情况,你应该定义你的默认路由 {控制器} / {行动} / {ID} ,把一个约束它。可能与控制器名称或者甚至行动。然后把包罗万象的一个接它,它应该工作得很好。

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.

所以,当有人要求一个失败的约束包罗万象的路线将匹配请求的资源。

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天全站免登陆