{}弹头格式 - {ID} ASP.NET MVC路线约束上 [英] ASP.NET MVC Route Contraints with {ID}-{Slug} Format

查看:95
本文介绍了{}弹头格式 - {ID} ASP.NET MVC路线约束上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有喜欢遵循的一条途径,最好我想它匹配的:

I have a route like following, ideally I would like it to match:

domain.com/layout/1-slug-is-the-name-of-the-page

domain.com/layout/1-slug-is-the-name-of-the-page

        routes.MapRoute(
            "Layout",                                                // Route name
            "layout/{id}-{slug}",                                           // URL with parameters
            new { controller = "Home", action = "Index"}, new {id = @"\d+$"}
        );

但是,当我打的网址,我不断收到此异常:

But when I hit the url, I am keep on getting this exception:

参数词典共包含非可空类型'System.Int32'的方法'System.Web.Mvc.ActionResult指数(Int32)已'参数'ID'空条目....

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in ....

上面的路由将匹配,虽然下面:

The above route will match the following though:

domain.com/layout/1-slug或domain.com/layout/1-slug_permalink

domain.com/layout/1-slug or domain.com/layout/1-slug_permalink

好像从弹头分离的ID是造成问题的连字符。

Seems like the hyphen that separates the ID from the Slug is causing issues.

推荐答案

作为处理的第一步,路由模块执行对申报途径传入URL的模式匹配。这种模式匹配渴望(这样的标识的获取所有连字符到最后一个,这标志着的蛞蝓的参数的开始)。约束(如\\ D +)模式匹配后运行。那么是什么绊倒您的是,急于模式匹配设置的标识的为无效值,那么它的失败的限制,这会导致全局路由不匹配,所以管道移动上试图匹配传入请求集合中的下一个路由。

As the first step of processing, the Routing module performs pattern matching of the incoming URL against the declared route. This pattern matching is eager (so the id gets all hyphens up to the last one, which marks the beginning of the slug parameter). Constraints (like "\d+") run after pattern matching. So what's tripping you up is that the eager pattern matching is setting id to an invalid value, then it's failing the constraint, which causes the overall route not to match, so the pipeline moves on trying to match the incoming request to the next route in the collection.

最好的(比如最简单的理解,不弄虚作假)的方式来解决,这是相匹配的整个段为的 idAndSlug 的参数,然后使用控制器内的适当的正则表达式来拆分此字符串背出到其的标识蛞蝓的成分。

The best (e.g. easiest to understand, non-trickery) way to work around this is to match the entire segment as an idAndSlug parameter, then use a proper regex within the controller to split this string back out into its id and slug constituents.

另外,可以考虑使用斜线,通过mxmissile的建议。

Alternatively, consider using the slash, as suggested by mxmissile.

这篇关于{}弹头格式 - {ID} ASP.NET MVC路线约束上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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